import { NextRequest, NextResponse } from 'next/server'
import { TOMDocumentAnalyzer } from '@/lib/sdk/tom-generator/ai/document-analyzer'
import { evidenceStore } from '@/lib/sdk/tom-generator/evidence-store'

/**
 * TOM Generator Evidence Analysis API
 *
 * POST /api/sdk/v1/tom-generator/evidence/[id]/analyze - Analyze evidence document with AI
 *
 * Request body:
 * {
 *   tenantId: string
 *   documentText?: string (if already extracted)
 * }
 */

export async function POST(
  request: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    const { id } = await params
    const body = await request.json()
    const { tenantId, documentText } = body

    if (!tenantId) {
      return NextResponse.json(
        { success: false, error: 'tenantId is required' },
        { status: 400 }
      )
    }

    // Get the document
    const document = await evidenceStore.getById(tenantId, id)
    if (!document) {
      return NextResponse.json(
        { success: false, error: `Document not found: ${id}` },
        { status: 404 }
      )
    }

    // Check if already analyzed
    if (document.aiAnalysis && document.status === 'ANALYZED') {
      return NextResponse.json({
        success: true,
        data: document.aiAnalysis,
        meta: {
          alreadyAnalyzed: true,
          analyzedAt: document.aiAnalysis.analyzedAt,
        },
      })
    }

    // Get document text (in production, this would be extracted from the file)
    const text = documentText || `[Document content from ${document.originalName}]`

    // Initialize analyzer
    const analyzer = new TOMDocumentAnalyzer()

    // Analyze the document
    const analysisResult = await analyzer.analyzeDocument(
      document,
      text,
      'de'
    )

    // Check if analysis was successful
    if (!analysisResult.success || !analysisResult.analysis) {
      return NextResponse.json(
        { success: false, error: analysisResult.error || 'Analysis failed' },
        { status: 500 }
      )
    }

    const analysis = analysisResult.analysis

    // Update the document with analysis results
    const updatedDocument = await evidenceStore.update(tenantId, id, {
      aiAnalysis: analysis,
      status: 'ANALYZED',
      linkedControlIds: [
        ...new Set([
          ...document.linkedControlIds,
          ...analysis.applicableControls,
        ]),
      ],
    })

    return NextResponse.json({
      success: true,
      data: {
        analysis,
        document: updatedDocument,
      },
      meta: {
        documentId: id,
        analyzedAt: analysis.analyzedAt,
        confidence: analysis.confidence,
        applicableControlsCount: analysis.applicableControls.length,
        gapsCount: analysis.gaps.length,
      },
    })
  } catch (error) {
    console.error('Failed to analyze evidence:', error)
    return NextResponse.json(
      { success: false, error: 'Failed to analyze evidence' },
      { status: 500 }
    )
  }
}

export async function OPTIONS() {
  return NextResponse.json(
    { status: 'ok' },
    {
      headers: {
        Allow: 'POST, OPTIONS',
      },
    }
  )
}
