export const dynamic = 'force-dynamic';

import { NextRequest, NextResponse } from 'next/server';
import { prisma } from '@/lib/db';
import { requireDFAuth } from '@/lib/dark-factory/auth-guard';
import { callLLM } from '@/lib/dark-factory/weft/llm';

// POST — generate visual artifacts from approved intake
export async function POST(req: NextRequest, { params }: { params: { id: string } }) {
  const authResult = await requireDFAuth();
  if (!authResult.authorized) return authResult.response;

  const intake = await prisma.dfIntake.findUnique({
    where: { id: params.id },
    include: { entities: true, acceptanceCriteria: true },
  });

  if (!intake) return NextResponse.json({ error: 'Intake not found' }, { status: 404 });
  if (intake.gate !== 'intake_approved') {
    return NextResponse.json({ error: `Intake must be in intake_approved state. Current: ${intake.gate}` }, { status: 400 });
  }

  const entityList = intake.entities.map(e => {
    const fields = Array.isArray(e.fields) ? (e.fields as Array<{name: string; type: string}>).map(f => `${f.name}: ${f.type}`).join(', ') : '';
    const rels = Array.isArray(e.relationships) ? (e.relationships as Array<{target: string; type: string}>).map(r => `→ ${r.target} (${r.type})`).join(', ') : '';
    return `${e.name}${fields ? ` [${fields}]` : ''}${rels ? ` ${rels}` : ''}`;
  }).join('\n');

  // Generate ERD
  const erdPrompt = `Generate a Mermaid.js Entity-Relationship Diagram for this system.

Project: ${intake.title}
Domain: ${intake.businessDomain}
Entities:\n${entityList || 'Infer from the problem statement below'}
Problem: ${intake.problemStatement}
Workflows: ${JSON.stringify(intake.coreWorkflows)}

Return ONLY the Mermaid erDiagram code block, no explanation. Include all entities with their key fields and relationships.`;

  // Generate User Flow
  const flowPrompt = `Generate a Mermaid.js flowchart showing the primary user workflow for this system.

Project: ${intake.title}
Problem: ${intake.problemStatement}
Target Users: ${JSON.stringify(intake.targetUsers)}
Workflows: ${JSON.stringify(intake.coreWorkflows)}

Return ONLY the Mermaid flowchart TD code block. Show the main user journey from start to completion.`;

  // Generate Sitemap/Screen Layout
  const sitemapPrompt = `Generate a Mermaid.js flowchart showing the screen/page structure of this application.

Project: ${intake.title}
Problem: ${intake.problemStatement}
Entities:\n${entityList}
Workflows: ${JSON.stringify(intake.coreWorkflows)}

Return ONLY the Mermaid flowchart TD code block. Show all major screens/pages and how they connect via navigation.`;

  try {
    const [erdContent, flowContent, sitemapContent] = await Promise.all([
      callLLM([{ role: 'user', content: erdPrompt }], { temperature: 0.2, maxTokens: 2000 }),
      callLLM([{ role: 'user', content: flowPrompt }], { temperature: 0.2, maxTokens: 1500 }),
      callLLM([{ role: 'user', content: sitemapPrompt }], { temperature: 0.2, maxTokens: 1500 }),
    ]);

    // Clean mermaid content
    const clean = (s: string) => s.replace(/```mermaid\n?|```\n?/g, '').trim();

    // Create visual records
    const visuals = await Promise.all([
      prisma.dfVisual.create({
        data: {
          intakeId: params.id, type: 'erd', title: 'Entity Relationship Diagram',
          description: 'Data model showing all entities and their relationships',
          content: clean(erdContent), status: 'draft', sortOrder: 0,
        },
      }),
      prisma.dfVisual.create({
        data: {
          intakeId: params.id, type: 'user_flow', title: 'Primary User Flow',
          description: 'Main user journey through the application',
          content: clean(flowContent), status: 'draft', sortOrder: 1,
        },
      }),
      prisma.dfVisual.create({
        data: {
          intakeId: params.id, type: 'sitemap', title: 'Application Screen Map',
          description: 'All screens/pages and navigation structure',
          content: clean(sitemapContent), status: 'draft', sortOrder: 2,
        },
      }),
    ]);

    await prisma.dfIntake.update({
      where: { id: params.id },
      data: { gate: 'visuals_generated' },
    });

    await prisma.dfRevisionLog.create({
      data: {
        intakeId: params.id, gate: 'intake_approved', action: 'visuals_generated',
        changedBy: 'system', reason: `Generated ${visuals.length} visual artifacts`,
      },
    });

    return NextResponse.json({ visuals, gate: 'visuals_generated' });
  } catch (error) {
    console.error('Visual generation error:', error);
    return NextResponse.json({ error: 'Failed to generate visuals' }, { status: 500 });
  }
}
