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 complexity estimate 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 });

  const prompt = `You are a senior software architect estimating project complexity.

Project: ${intake.title}
Domain: ${intake.businessDomain}
Problem: ${intake.problemStatement}
Target Stack: ${intake.targetLanguage} + ${intake.targetDatabase}
Entities: ${intake.entities.map(e => e.name).join(', ') || 'Not yet defined'}
Entity Count: ${intake.entities.length}
Workflows: ${JSON.stringify(intake.coreWorkflows)}
Integrations: ${JSON.stringify(intake.integrations)}
Constraints: ${JSON.stringify(intake.constraints)}
Acceptance Criteria: ${intake.acceptanceCriteria.map(c => c.description).join('; ') || 'None defined'}

Provide a JSON estimate:
{
  "complexityScore": <1-10>,
  "estimatedHours": <developer hours for traditional build>,
  "estimatedCost": <USD at $150/hr>,
  "dfEstimatedHours": <hours using The Hearth>,
  "dfEstimatedCost": <USD at $75/hr with DF>,
  "riskFactors": ["list of technical risks"],
  "reasoning": "brief explanation"
}`;

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

    let estimate;
    try {
      const cleaned = response.replace(/```json\n?|```\n?/g, '').trim();
      estimate = JSON.parse(cleaned);
    } catch {
      estimate = { complexityScore: 5, estimatedHours: 80, estimatedCost: 12000, dfEstimatedHours: 20, dfEstimatedCost: 1500, riskFactors: [], reasoning: response };
    }

    await prisma.dfIntake.update({
      where: { id: params.id },
      data: {
        complexityScore: estimate.complexityScore || 5,
        estimatedHours: estimate.estimatedHours || 80,
        estimatedCost: estimate.estimatedCost || 12000,
        entityCount: intake.entities.length,
      },
    });

    return NextResponse.json({ estimate });
  } catch (error) {
    console.error('Estimate generation error:', error);
    return NextResponse.json({ error: 'Failed to generate estimate' }, { status: 500 });
  }
}
