/**
 * ${VOCAB.factory} RAG Router API
 * Phase 1: RAG-Augmented Routing System
 * 
 * POST /api/dark-factory/route
 * Analyzes a prompt and returns routing decision
 */

import { NextRequest, NextResponse } from 'next/server';
import { routePrompt, explainRouting, logRoutingDecision, RouterConfig } from '@/lib/dark-factory/rag/router';
import { 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();
    const { prompt, config } = body as {
      prompt: string;
      config?: RouterConfig;
    };

    if (!prompt || typeof prompt !== 'string') {
      return NextResponse.json(
        { error: 'Prompt is required and must be a string' },
        { status: 400 }
      );
    }

    // Route the prompt
    const decision = routePrompt(prompt, config || {});
    
    // Log for analytics
    logRoutingDecision(decision);

    // Return routing decision
    return NextResponse.json({
      success: true,
      decision: {
        model: decision.model,
        systemPrompt: decision.systemPrompt,
        contextInjection: decision.contextInjection,
        analysis: {
          taskType: decision.analysis.taskType,
          complexity: decision.analysis.complexity,
          domain: decision.analysis.domain,
          confidence: decision.analysis.confidence,
          estimatedTokens: decision.analysis.estimatedTokens,
          reasoning: decision.analysis.reasoning,
          detectedPatterns: decision.analysis.detectedPatterns
        },
        metadata: decision.metadata
      },
      explanation: explainRouting(decision)
    });
  } catch (error) {
    console.error(`${VOCAB.factory} Router Error:`, error);
    return NextResponse.json(
      { error: 'Failed to route prompt', details: error instanceof Error ? error.message : 'Unknown error' },
      { status: 500 }
    );
  }
}

export async function GET() {
  const auth = await requireDFAuth();
  if (!auth.authorized) return auth.response;

  return NextResponse.json({
    service: `${VOCAB.factory} RAG Router`,
    version: '1.0.0-phase1',
    status: 'operational',
    endpoints: {
      'POST /api/dark-factory/route': 'Route a prompt to the optimal model',
    },
    supportedModels: [
      'claude-sonnet-4.6',
      'claude-opus-4.6', 
      'claude-haiku-4.5',
      'o3',
      'o4-mini',
      'deepseek-v3.1',
      'gpt-4.1',
      'gemini-2.5-pro'
    ]
  });
}
