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 deliverable plan from approved visuals
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, visuals: true, acceptanceCriteria: true },
  });

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

  const prompt = `You are a senior software architect defining deliverables for a code generation pipeline.

Project: ${intake.title}
Domain: ${intake.businessDomain}
Problem: ${intake.problemStatement}
Stack: ${intake.targetLanguage} + ${intake.targetDatabase}
Entities: ${intake.entities.map(e => e.name).join(', ')}
Visual Artifacts: ${intake.visuals.map(v => `${v.type}: ${v.title}`).join(', ')}
Acceptance Criteria: ${intake.acceptanceCriteria.map(c => c.description).join('; ')}

Define the complete list of deliverables that the code generation pipeline should produce.
For each deliverable, specify its type and what it should contain.

Return JSON array:
[
  { "name": "string", "type": "api_route|ui_component|data_model|config|documentation|test", "description": "what this deliverable contains", "acceptanceCriteria": "how to verify it works" }
]

Be thorough — include API routes for each entity (CRUD), UI components for each screen, data models, configuration files, documentation (API docs, setup guide, README), and test specifications.`;

  try {
    const response = await callLLM(
      [{ role: 'user', content: prompt }],
      { temperature: 0.3, maxTokens: 3000, jsonMode: true }
    );

    let deliverableList;
    try {
      const cleaned = response.replace(/```json\n?|```\n?/g, '').trim();
      deliverableList = JSON.parse(cleaned);
    } catch {
      return NextResponse.json({ error: 'Failed to parse deliverable list from LLM' }, { status: 500 });
    }

    if (!Array.isArray(deliverableList)) {
      return NextResponse.json({ error: 'LLM returned non-array deliverable list' }, { status: 500 });
    }

    const deliverables = await Promise.all(
      deliverableList.map((d: { name: string; type: string; description: string; acceptanceCriteria?: string }, i: number) =>
        prisma.dfDeliverable.create({
          data: {
            intakeId: params.id,
            name: d.name,
            type: d.type || 'api_route',
            description: d.description || '',
            acceptanceCriteria: d.acceptanceCriteria || '',
            status: 'planned',
            sortOrder: i,
          },
        })
      )
    );

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

    await prisma.dfRevisionLog.create({
      data: {
        intakeId: params.id, gate: 'visuals_approved', action: 'deliverables_generated',
        changedBy: 'system', reason: `Generated ${deliverables.length} deliverable definitions`,
      },
    });

    return NextResponse.json({ deliverables, gate: 'deliverables_defined' });
  } catch (error) {
    console.error('Deliverable generation error:', error);
    return NextResponse.json({ error: 'Failed to generate deliverables' }, { status: 500 });
  }
}
