/**
 * ${VOCAB.factory} - Generation API (Standalone Pipeline)
 * POST /api/dark-factory/generate
 * 
 * Accepts an engineered prompt and generates a complete software solution.
 * Uses the standalone agent hierarchy (Architect → Prompt Engineer → Code Engineer → Review → QA)
 * with a 97% quality gate before marking complete.
 *
 * Supports language selection, database selection, expert mode specs, and deployment targets.
 * Returns immediately with taskId - client polls for status.
 *
 * This endpoint operates fully standalone — no FF dependency.
 */

import { NextRequest, NextResponse } from 'next/server';
import { runStandalonePipeline, StandalonePipelineRequest } from '@/lib/dark-factory/agents/standalone-pipeline';
import { prisma } from '@/lib/db';
import { VOCAB } from '@/lib/white-label/constants';
import { requireDFAuth } from '@/lib/dark-factory/auth-guard';
import { LANGUAGE_OPTIONS, DATABASE_OPTIONS } from '@/lib/dark-factory/types/generation-options';

export const dynamic = 'force-dynamic';
export const maxDuration = 300; // Allow up to 5 minutes for long generation

export async function POST(request: NextRequest) {
  const auth = await requireDFAuth();
  if (!auth.authorized) return auth.response;

  try {
    const body = await request.json();
    
    // Validate required fields
    if (!body.prompt || typeof body.prompt !== 'string') {
      return NextResponse.json(
        { error: 'Missing required field: prompt' },
        { status: 400 }
      );
    }

    // Validate language if provided
    if (body.language && !LANGUAGE_OPTIONS.find((l) => l.id === body.language)) {
      return NextResponse.json(
        { error: `Unsupported language: ${body.language}. Supported: ${LANGUAGE_OPTIONS.map(l => l.id).join(', ')}` },
        { status: 400 }
      );
    }

    // Validate database if provided
    if (body.database && !DATABASE_OPTIONS.find((d) => d.id === body.database)) {
      return NextResponse.json(
        { error: `Unsupported database: ${body.database}. Supported: ${DATABASE_OPTIONS.map(d => d.id).join(', ')}` },
        { status: 400 }
      );
    }

    // Validate projectId if provided
    if (body.projectId) {
      const project = await prisma.darkFactoryProject.findUnique({
        where: { id: body.projectId },
      });
      if (!project) {
        return NextResponse.json(
          { error: 'Project not found' },
          { status: 404 }
        );
      }
    }

    // Create a pending request record
    const dbRequest = await prisma.generationRequest.create({
      data: {
        prompt: body.prompt,
        context: body.context ? JSON.parse(JSON.stringify(body.context)) : null,
        priority: body.priority || 'normal',
        requestedBy: body.requestedBy || 'human',
        status: 'pending',
        projectId: body.projectId || null,
      },
    });

    // Build standalone pipeline request
    const pipelineRequest: StandalonePipelineRequest = {
      prompt: body.prompt,
      language: body.language || 'typescript-react',
      database: body.database || 'postgresql',
      projectId: body.projectId,
      expertSpec: body.expertSpec || undefined,
      llmConfig: body.llmConfig || undefined,
      deploymentTargets: body.deploymentTargets || ['web'],
    };

    // Start generation in background (don't await)
    runPipelineInBackground(dbRequest.id, pipelineRequest);

    // Return immediately with task info
    return NextResponse.json({
      success: true,
      taskId: dbRequest.id,
      status: 'processing',
      pipeline: 'standalone',
      agents: ['architect', 'prompt-engineer', 'code-engineer', 'review-agent', 'qa-agent'],
      qualityGate: { minReviewScore: 97, minTestAccuracy: 97 },
      message: 'Generation started. Architect is delegating to the agent pipeline. Poll /api/dark-factory/status/{taskId} for progress.',
    });

  } catch (error) {
    console.error(`${VOCAB.factory} generation error:`, error);
    return NextResponse.json(
      { 
        error: 'Generation failed', 
        details: error instanceof Error ? error.message : 'Unknown error' 
      },
      { status: 500 }
    );
  }
}

// Run the standalone pipeline in background - status tracked via database
async function runPipelineInBackground(requestId: string, pipelineRequest: StandalonePipelineRequest) {
  try {
    console.log(`[${VOCAB.factory}] Starting standalone pipeline for ${requestId} (lang: ${pipelineRequest.language}, db: ${pipelineRequest.database})`);
    
    const result = await runStandalonePipeline(pipelineRequest);
    
    // Map pipeline status to request status
    const requestStatus = result.status === 'failed' ? 'failed'
      : result.status === 'needs_human_review' ? 'needs_review'
      : 'completed';

    await prisma.generationRequest.update({
      where: { id: requestId },
      data: { status: requestStatus },
    });

    console.log(`[${VOCAB.factory}] Standalone pipeline completed for ${requestId}: ${result.status} (Review: ${result.qualityReport?.reviewScore ?? 'N/A'}%, Tests: ${result.qualityReport?.testAccuracy ?? 'N/A'}%)`);

  } catch (error) {
    console.error(`[${VOCAB.factory}] Standalone pipeline failed for ${requestId}:`, error);
    
    await prisma.generationRequest.update({
      where: { id: requestId },
      data: { status: 'failed' },
    }).catch((e: any) => console.error('Failed to update request status:', e));
  }
}
