import { NextRequest, NextResponse } from 'next/server';
import { MetaAIClient } from '@/lib/providers/meta-client';

export async function POST(req: NextRequest) {
    try {
        const { prompt, cookies, imageCount = 4, aspectRatio = 'portrait', useMetaFreeWrapper, metaFreeWrapperUrl } = await req.json();

        if (!prompt) {
            return NextResponse.json({ error: "Prompt is required" }, { status: 400 });
        }

        // Only check for cookies if NOT using free wrapper
        if (!useMetaFreeWrapper && !cookies) {
            return NextResponse.json(
                { error: "Meta AI cookies required. Configure in Settings or use Free Wrapper." },
                { status: 401 }
            );
        }

        console.log(`[Meta AI Route] Generating images for: "${prompt.substring(0, 30)}..." (${aspectRatio})`);

        // Diagnostic: Check how many cookies we received
        try {
            const parsed = typeof cookies === 'string' && cookies.trim().startsWith('[')
                ? JSON.parse(cookies)
                : cookies;
            const count = Array.isArray(parsed) ? parsed.length : (typeof cookies === 'string' ? cookies.split(';').length : 0);
            console.log(`[Meta AI Route] Received ${count} cookies (Free Wrapper: ${useMetaFreeWrapper})`);
        } catch {
            console.log(`[Meta AI Route] Cookie format: ${typeof cookies}`);
        }

        const client = new MetaAIClient({
            cookies: cookies || '',
            useFreeWrapper: useMetaFreeWrapper,
            freeWrapperUrl: metaFreeWrapperUrl
        });
        const results = await client.generate(prompt, imageCount, aspectRatio);

        // Download images as base64 for storage
        const images = await Promise.all(
            results.map(async (img) => {
                let base64 = img.data;
                if (!base64 && img.url) {
                    try {
                        base64 = await client.downloadAsBase64(img.url);
                    } catch (e) {
                        console.warn("[Meta AI Route] Failed to download image:", e);
                    }
                }
                return {
                    data: base64 || '',
                    url: img.url,
                    prompt: img.prompt,
                    model: img.model,
                    aspectRatio: '1:1' // Meta AI default
                };
            })
        );

        const validImages = images.filter(img => img.data || img.url);

        if (validImages.length === 0) {
            throw new Error("No valid images generated");
        }

        return NextResponse.json({ success: true, images: validImages });

    } catch (error: any) {
        console.error("[Meta AI Route] Error:", error);
        return NextResponse.json(
            { error: error.message || "Meta AI generation failed" },
            { status: 422 } // Use 422 instead of 500 to avoid Next.js rendering error pages
        );
    }
}
