import { NextResponse } from 'next/server';
import fs from 'fs/promises';
import path from 'path';
import { PromptCache } from '@/lib/types';
import { WhiskClient } from '@/lib/whisk-client';

const DATA_FILE = path.join(process.cwd(), 'data', 'prompts.json');
const PUBLIC_DIR = path.join(process.cwd(), 'public');

export async function POST(req: Request) {
    try {
        const { id, prompt, cookies } = await req.json();

        if (!id || !prompt || !cookies) {
            return NextResponse.json({ error: 'Missing required fields' }, { status: 400 });
        }

        console.log(`[API] Generating preview for prompt ${id}...`);

        // 1. Generate Image (Server-Side)
        const client = new WhiskClient(cookies);
        const images = await client.generate(prompt, "1:1"); // Square

        if (!images || images.length === 0) {
            return NextResponse.json({ error: 'Generation returned no images' }, { status: 500 });
        }

        const imageBase64 = images[0].data;

        // 2. Save Image
        const base64Data = imageBase64.replace(/^data:image\/\w+;base64,/, "");
        const buffer = Buffer.from(base64Data, 'base64');
        const filename = `prompt_${id}_${Date.now()}.png`;
        const relativePath = `/prompts/${filename}`;
        const fullPath = path.join(PUBLIC_DIR, 'prompts', filename);

        // Ensure dir exists
        await fs.mkdir(path.dirname(fullPath), { recursive: true });
        await fs.writeFile(fullPath, buffer);

        // 3. Update Prompt Cache
        const fileContent = await fs.readFile(DATA_FILE, 'utf-8');
        const cache: PromptCache = JSON.parse(fileContent);

        const promptIndex = cache.prompts.findIndex(p => p.id === id);
        if (promptIndex !== -1) {
            if (!cache.prompts[promptIndex].images) {
                cache.prompts[promptIndex].images = [];
            }
            cache.prompts[promptIndex].images.unshift(relativePath);

            await fs.writeFile(DATA_FILE, JSON.stringify(cache, null, 2), 'utf-8');
        }

        return NextResponse.json({ success: true, url: relativePath });

    } catch (error: any) {
        console.error("Generation API failed:", error);

        const msg = error.message || '';
        if (msg.includes("Safety Filter") || msg.includes("PROMINENT_PEOPLE") || msg.includes("UNSAFE")) {
            return NextResponse.json({ error: 'Content Blocked by Safety Filters', code: 'SAFETY_FILTER' }, { status: 422 });
        }

        return NextResponse.json({ error: error.message || 'Generation failed' }, { status: 500 });
    }
}
