/**
 * ${VOCAB.factory} - Expert Preview API
 * POST /api/dark-factory/expert-preview
 * 
 * Calls the LLM to design architecture and returns it for user editing
 * before actual code generation starts.
 */

import { NextRequest, NextResponse } from 'next/server';
import { BRAND, VOCAB } from '@/lib/white-label/constants';
import { requireDFAuth } from '@/lib/dark-factory/auth-guard';

export const dynamic = 'force-dynamic';

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

  try {
    const body = await request.json();

    if (!body.prompt || typeof body.prompt !== 'string') {
      return NextResponse.json({ error: 'Missing required field: prompt' }, { status: 400 });
    }

    const apiKey = process.env.ABACUSAI_API_KEY;
    if (!apiKey) {
      return NextResponse.json({ error: 'LLM API key not configured' }, { status: 500 });
    }

    const { prompt, language, database, context } = body;

    const systemPrompt = `You are Weft, an expert software architect for ${BRAND.companyName}'s ${VOCAB.factory}.

Your job is to design a preliminary architecture for the user's request so they can review/edit BEFORE code generation.

Target Language: ${language || 'typescript-react'}
Target Database: ${database || 'postgresql'}

Respond with ONLY valid JSON (no markdown, no explanation):
{
  "summary": "One-line description of the module",
  "entities": [
    {
      "name": "EntityName",
      "description": "Purpose of this entity",
      "fields": [
        { "name": "id", "type": "String", "required": true, "description": "Primary key" },
        { "name": "createdAt", "type": "DateTime", "required": true, "description": "Created timestamp" },
        { "name": "updatedAt", "type": "DateTime", "required": true, "description": "Updated timestamp" }
      ],
      "relations": [
        { "name": "relName", "type": "one-to-many", "target": "OtherEntity", "description": "Relation desc" }
      ]
    }
  ],
  "endpoints": [
    {
      "path": "/api/module",
      "method": "GET",
      "description": "What it does",
      "businessLogic": ["Step 1"]
    }
  ],
  "namingConventions": {
    "modelCase": "PascalCase",
    "fieldCase": "camelCase",
    "endpointCase": "kebab-case",
    "fileNaming": "kebab-case"
  }
}

Field types: String, Int, Float, Decimal, Boolean, DateTime, Json
Method types: GET, POST, PUT, DELETE, PATCH
Keep it concise: 3-5 entities, 5-10 endpoints.`;

    let userPrompt = `Design a module for:\n\n"${prompt}"`;
    if (context?.businessDomain) {
      userPrompt += `\n\nBusiness Domain: ${context.businessDomain}`;
    }
    if (context?.existingEntities?.length) {
      userPrompt += `\n\nExisting entities: ${context.existingEntities.join(', ')}`;
    }

    const controller = new AbortController();
    const timeoutId = setTimeout(() => controller.abort(), 60000);

    try {
      const response = await fetch('https://routellm.abacus.ai/v1/chat/completions', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${apiKey}`,
        },
        body: JSON.stringify({
          model: 'claude-sonnet-4-20250514',
          messages: [
            { role: 'system', content: systemPrompt },
            { role: 'user', content: userPrompt },
          ],
          response_format: { type: 'json_object' },
          max_tokens: 3000,
          temperature: 0.3,
        }),
        signal: controller.signal,
      });

      clearTimeout(timeoutId);

      if (!response.ok) {
        const errText = await response.text();
        console.error('[Expert Preview] LLM error:', errText.substring(0, 200));
        return NextResponse.json({ error: 'Failed to generate preview' }, { status: 502 });
      }

      const data = await response.json();
      const content = data.choices?.[0]?.message?.content;

      if (!content) {
        return NextResponse.json({ error: 'Empty LLM response' }, { status: 502 });
      }

      // Parse and validate the architecture
      let parsed;
      try {
        parsed = JSON.parse(content);
      } catch {
        // Try extracting JSON from code block
        const jsonMatch = content.match(/```(?:json)?\n?([\s\S]*?)```/);
        if (jsonMatch) {
          parsed = JSON.parse(jsonMatch[1].trim());
        } else {
          const objMatch = content.match(/\{[\s\S]*\}/);
          if (objMatch) {
            parsed = JSON.parse(objMatch[0]);
          } else {
            throw new Error('Could not parse JSON');
          }
        }
      }

      // Ensure naming conventions have defaults
      if (!parsed.namingConventions) {
        parsed.namingConventions = {
          modelCase: 'PascalCase',
          fieldCase: 'camelCase',
          endpointCase: 'kebab-case',
          fileNaming: 'kebab-case',
        };
      }

      return NextResponse.json({ success: true, spec: parsed });

    } catch (fetchError) {
      clearTimeout(timeoutId);
      if (fetchError instanceof Error && fetchError.name === 'AbortError') {
        return NextResponse.json({ error: 'Preview request timed out' }, { status: 504 });
      }
      throw fetchError;
    }

  } catch (error) {
    console.error('[Expert Preview] Error:', error);
    return NextResponse.json(
      { error: 'Failed to generate preview', details: error instanceof Error ? error.message : 'Unknown' },
      { status: 500 }
    );
  }
}
