import { getCoverImage, getPageContent } from "$lib/server/nextcloud";
import type { PageServerLoad } from "./$types";
import { error } from "@sveltejs/kit";

export const load: PageServerLoad = async ({ params }) => {
    const { slug, lang } = params;
    const language = lang || 'de';

    // Try both the regular slug and the hidden (_slug) folder
    const slugsToTry = [slug, `_${slug}`];
    let rawContent = "";
    let finalSlug = slug;
    let baseName = "";
    let filename = "";

    for (const s of slugsToTry) {
        const cleanSlug = s.startsWith('_') ? s.slice(1) : s;
        baseName = cleanSlug.charAt(0).toUpperCase() + cleanSlug.slice(1);
            
        filename = language === 'de' ? `${baseName}.md` : `${baseName}.${language}.md`;
        const path = `/${s}/${filename}`;

        try {
            try {
                rawContent = await getPageContent(path);
                finalSlug = s;
                break; // Found it!
            } catch (e) {
                if (language !== 'de') {
                    console.warn(`Localized content ${filename} not found in ${s}, falling back to German.`);
                    rawContent = await getPageContent(`/${s}/${baseName}.md`);
                    finalSlug = s;
                    break; // Found fallback
                } else {
                    throw e; // Try next slug variant
                }
            }
        } catch (e) {
            if (s === slugsToTry[slugsToTry.length - 1]) {
                console.error(`Error fetching page from Nextcloud for slug ${slug}`, e);
                throw error(404, "Page not found");
            }
        }
    }

    try {
        // Extract the first header (e.g., # Title or ## Title)
        const headerMatch = rawContent.match(/^#{1,6}\s+(.+)$/m);
        const title = headerMatch ? headerMatch[1] : (finalSlug.startsWith('_') ? finalSlug.slice(1) : finalSlug);
        
        // Remove the first header from content so it's not rendered twice
        const content = headerMatch 
            ? rawContent.replace(headerMatch[0], "").trim() 
            : rawContent;

        const coverImage = await getCoverImage(finalSlug);

        return {
            content,
            title,
            slug: finalSlug,
            coverImage,
            lang: language
        };
    } catch (e) {
        console.error(`Error processing content for ${finalSlug}`, e);
        throw error(404, "Page not found");
    }
};