import { NextRequest, NextResponse } from 'next/server';

export const dynamic = 'force-dynamic';
export const maxDuration = 60;

const SYSTEM_PROMPT = `You are ScopeHarvester, a data engineering architect specializing in building private LLM training datasets.

Given a business description and intended LLM use case, produce a comprehensive data collection plan.

Return ONLY valid JSON:
{
  "businessAnalysis": {
    "domain": "detected industry/domain",
    "llmPurpose": "what this private LLM would do",
    "estimatedCorpusSize": "e.g., 50-200GB",
    "estimatedTokens": "e.g., 25-100B tokens",
    "trainingTimeEstimate": "e.g., 2-4 weeks on 8xA100"
  },
  "dataSources": [
    {
      "category": "Internal Documents",
      "sources": [
        {
          "name": "SOPs & Process Documentation",
          "description": "Standard operating procedures, runbooks, internal wikis",
          "format": "PDF, Confluence, Notion",
          "priority": "HIGH",
          "estimatedSize": "5-20GB",
          "collectionMethod": "API export from wiki platform + PDF scraping",
          "privacyNotes": "Redact employee PII before ingestion"
        }
      ]
    }
  ],
  "dataQualityChecklist": [
    { "check": "PII Redaction", "description": "Remove all personally identifiable information", "critical": true },
    { "check": "Deduplication", "description": "Remove duplicate documents to avoid training bias", "critical": true }
  ],
  "pipelineSteps": [
    { "step": 1, "name": "Collection", "description": "Gather raw data from all identified sources", "duration": "1-2 weeks" }
  ],
  "risks": [
    { "risk": "Data staleness", "mitigation": "Set up incremental refresh pipeline", "severity": "MEDIUM" }
  ],
  "estimatedBudget": {
    "dataCollection": "$5,000-15,000",
    "preprocessing": "$3,000-8,000",
    "training": "$10,000-50,000",
    "totalRange": "$18,000-73,000"
  }
}

Provide 4-7 data source categories with 2-4 specific sources each.
Be specific to the business domain. A law firm needs different data than a restaurant chain.
Include at least 6 quality checks, 5 pipeline steps, and 3 risks.
Be practical and realistic about costs and timelines.`;

export async function POST(request: NextRequest) {
  try {
    const { business, useCase } = await request.json();

    if (!business || business.trim().length < 20) {
      return NextResponse.json({ error: 'Please describe your business in at least 20 characters.' }, { status: 400 });
    }

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

    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: SYSTEM_PROMPT },
          { role: 'user', content: `Business: ${business}\n\n${useCase ? `Intended LLM use case: ${useCase}` : 'General-purpose business LLM for internal knowledge and automation.'}` },
        ],
        temperature: 0.3,
        max_tokens: 6000,
      }),
    });

    if (!response.ok) return NextResponse.json({ error: 'Service unavailable.' }, { status: 502 });

    const data = await response.json();
    const content = data.choices?.[0]?.message?.content || '';
    const jsonMatch = content.match(/```(?:json)?\s*([\s\S]*?)```/) || [null, content];
    const plan = JSON.parse((jsonMatch[1] || content).trim());
    return NextResponse.json(plan);
  } catch (error) {
    console.error('ScopeHarvester error:', error);
    return NextResponse.json({ error: 'Failed to generate plan.' }, { status: 500 });
  }
}
