import { createClient } from "webdav";
import { env } from "$env/dynamic/private";
import { withCache } from "./cache";

if (!env.NEXTCLOUD_URL || !env.NEXTCLOUD_USER || !env.NEXTCLOUD_PASSWORD) {
  console.warn(
    "Nextcloud environment variables are not fully set. WebDAV client might not work correctly.",
  );
}

// Construct the standard Nextcloud WebDAV URL: https://example.com/remote.php/dav/files/USERNAME/[BASE_DIR/]
const getWebdavUrl = () => {
  if (!env.NEXTCLOUD_URL) return "";

  let url = env.NEXTCLOUD_URL.endsWith("/")
    ? env.NEXTCLOUD_URL
    : `${env.NEXTCLOUD_URL}/`;
  url += `remote.php/dav/files/${env.NEXTCLOUD_USER}/`;

  if (env.NEXTCLOUD_BASE_DIR) {
    // Remove leading/trailing slashes from base dir to ensure clean concatenation
    const baseDir = env.NEXTCLOUD_BASE_DIR.replace(/^\/+|\/+$/g, "");
    if (baseDir) {
      url += `${baseDir}/`;
    }
  }

  return url;
};

export const client = createClient(getWebdavUrl(), {
  username: env.NEXTCLOUD_USER || "",
  password: env.NEXTCLOUD_PASSWORD || "",
});

export async function getCoverImage(slug: string): Promise<string | null> {
  return withCache(`cover:${slug}`, async () => {
    try {
      const contents = await client.getDirectoryContents("/" + slug);
      if (!Array.isArray(contents)) return null;

      const cover = contents.find(
        (item: any) =>
          item.type === "file" &&
          item.basename.match(/^cover\.(webp|jpg|jpeg|png)$/i),
      );

      return cover ? `/assets/${slug}/${cover.basename}` : null;
    } catch (e) {
      console.warn(`Failed to check cover image for ${slug}:`, e);
      return null;
    }
  });
}

export async function getPages(lang: string = 'de') {
  return withCache(`pages:${lang}`, async () => {
    try {
      const items = await client.getDirectoryContents("/");

      if (!Array.isArray(items)) {
        return [];
      }

      const directories = items.filter(
        (item: any) =>
          item.type === "directory" && 
          !item.basename.startsWith(".") && 
          !item.basename.startsWith("_"),
      );

      const pages = await Promise.all(
        directories.map(async (item: any) => {
          const slug = item.basename;
          const baseName = slug.charAt(0).toUpperCase() + slug.slice(1);
          const filename = lang === 'de' ? `${baseName}.md` : `${baseName}.${lang}.md`;
          const path = `/${slug}/${filename}`;
          
          let title = baseName;
          try {
            const content = await getPageContent(path);
            const headerMatch = content.match(/^#{1,6}\s+(.+)$/m);
            if (headerMatch) {
              title = headerMatch[1];
            }
          } catch (e) {
            // Fallback to German if English is missing
            if (lang !== 'de') {
              try {
                const fallbackContent = await getPageContent(`/${slug}/${baseName}.md`);
                const headerMatch = fallbackContent.match(/^#{1,6}\s+(.+)$/m);
                if (headerMatch) {
                  title = headerMatch[1];
                }
              } catch (innerE) {
                console.warn(`Could not fetch fallback title for ${slug}`);
              }
            }
          }

          const coverImage = await getCoverImage(slug);

          return {
            slug,
            title,
            coverImage,
          };
        }),
      );

      return pages;
    } catch (e) {
      console.error("Failed to fetch pages from Nextcloud:", e);
      return [];
    }
  });
}

export async function getPageContent(path: string): Promise<string> {
  return withCache(`content:${path}`, async () => {
    const content = await client.getFileContents(path, { format: "text" });
    return content as string;
  });
}
