import { NextRequest, NextResponse } from 'next/server'
import { v4 as uuidv4 } from 'uuid'
import {
  Finding,
  CONTRACT_REVIEW_SYSTEM_PROMPT,
} from '@/lib/sdk/vendor-compliance'
import { queryRAG } from '@/lib/sdk/drafting-engine/rag-query'
import { transformAnalysisResponse } from '@/lib/sdk/vendor-compliance/contract-review/analyzer'
import { cascadeComplete } from '@/lib/sdk/drafting-engine/llm-cascade'

/**
 * POST /api/sdk/v1/vendor-compliance/contracts/[id]/review
 *
 * Starts the LLM-based contract review process.
 * If documentText is provided, runs LLM analysis with RAG context.
 * Falls back to mock findings on LLM error or missing documentText.
 */
export async function POST(
  request: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    const { id: contractId } = await params
    const body = await request.json().catch(() => ({}))
    const { documentText, vendorId, tenantId } = body as {
      documentText?: string
      vendorId?: string
      tenantId?: string
    }

    // If documentText is provided, attempt LLM-based analysis
    if (documentText) {
      try {
        // Fetch RAG context for contract review
        const ragContext = await queryRAG(
          'AVV Art. 28 DSGVO Auftragsverarbeitung Vertragsanforderungen',
          3,
          'bp_compliance_recht'
        )

        // Build system prompt with RAG context
        let systemPrompt = CONTRACT_REVIEW_SYSTEM_PROMPT
        if (ragContext) {
          systemPrompt += `\n\nRECHTSKONTEXT (als Referenz):\n${ragContext}`
        }

        // Call Ollama
        const llm = await cascadeComplete(
          [
            { role: 'system', content: systemPrompt },
            { role: 'user', content: `Analysiere den folgenden Vertrag auf DSGVO-Konformitaet:\n\n${documentText}` },
          ],
          { json: true, temperature: 0.1, maxTokens: 16384, timeoutMs: 180000 },
        )

        if (!llm) {
          throw new Error('LLM nicht erreichbar (weder OVH noch Ollama)')
        }

        const llmResponse = JSON.parse(llm.content)

        // Transform LLM response to typed findings
        const analysisResult = transformAnalysisResponse(llmResponse, {
          contractId,
          vendorId: vendorId || 'unknown',
          tenantId: tenantId || 'default',
          documentText,
        })

        return NextResponse.json({
          success: true,
          data: {
            contractId,
            findings: analysisResult.findings,
            complianceScore: analysisResult.complianceScore,
            reviewCompletedAt: new Date().toISOString(),
            topRisks: analysisResult.topRisks,
            requiredActions: analysisResult.requiredActions,
            metadata: analysisResult.metadata,
            parties: analysisResult.parties,
            source: 'llm',
          },
          timestamp: new Date().toISOString(),
        })
      } catch (error) {
        console.warn('LLM contract review failed, falling back to mock:', (error as Error).message)
        // Fall through to mock findings
      }
    }

    // Fallback: Mock analysis results
    const mockFindings: Finding[] = [
      {
        id: uuidv4(),
        tenantId: 'default',
        contractId,
        vendorId: 'mock-vendor',
        type: 'OK',
        category: 'AVV_CONTENT',
        severity: 'LOW',
        title: {
          de: 'Weisungsgebundenheit vorhanden',
          en: 'Instruction binding present',
        },
        description: {
          de: 'Der Vertrag enthält eine angemessene Regelung zur Weisungsgebundenheit des Auftragsverarbeiters.',
          en: 'The contract contains an appropriate provision for processor instruction binding.',
        },
        citations: [
          {
            documentId: contractId,
            page: 2,
            startChar: 150,
            endChar: 350,
            quotedText: 'Der Auftragnehmer verarbeitet personenbezogene Daten ausschließlich auf dokumentierte Weisung des Auftraggebers.',
            quoteHash: 'abc123',
          },
        ],
        affectedRequirement: 'Art. 28 Abs. 3 lit. a DSGVO',
        triggeredControls: ['VND-CON-01'],
        status: 'OPEN',
        createdAt: new Date(),
        updatedAt: new Date(),
      },
      {
        id: uuidv4(),
        tenantId: 'default',
        contractId,
        vendorId: 'mock-vendor',
        type: 'GAP',
        category: 'INCIDENT',
        severity: 'HIGH',
        title: {
          de: 'Meldefrist für Datenpannen zu lang',
          en: 'Data breach notification deadline too long',
        },
        description: {
          de: 'Die vereinbarte Meldefrist von 72 Stunden ist zu lang, um die eigene Meldepflicht gegenüber der Aufsichtsbehörde fristgerecht erfüllen zu können.',
          en: 'The agreed notification deadline of 72 hours is too long to meet own notification obligations to the supervisory authority in time.',
        },
        recommendation: {
          de: 'Verhandeln Sie eine kürzere Meldefrist von maximal 24-48 Stunden.',
          en: 'Negotiate a shorter notification deadline of maximum 24-48 hours.',
        },
        citations: [
          {
            documentId: contractId,
            page: 5,
            startChar: 820,
            endChar: 950,
            quotedText: 'Der Auftragnehmer wird den Auftraggeber innerhalb von 72 Stunden über eine Verletzung des Schutzes personenbezogener Daten informieren.',
            quoteHash: 'def456',
          },
        ],
        affectedRequirement: 'Art. 33 Abs. 2 DSGVO',
        triggeredControls: ['VND-INC-01'],
        status: 'OPEN',
        createdAt: new Date(),
        updatedAt: new Date(),
      },
      {
        id: uuidv4(),
        tenantId: 'default',
        contractId,
        vendorId: 'mock-vendor',
        type: 'RISK',
        category: 'TRANSFER',
        severity: 'MEDIUM',
        title: {
          de: 'Drittlandtransfer USA ohne TIA',
          en: 'Third country transfer to USA without TIA',
        },
        description: {
          de: 'Der Vertrag erlaubt Datenverarbeitung in den USA. Es liegt jedoch kein Transfer Impact Assessment (TIA) vor.',
          en: 'The contract allows data processing in the USA. However, no Transfer Impact Assessment (TIA) is available.',
        },
        recommendation: {
          de: 'Führen Sie ein TIA durch und dokumentieren Sie zusätzliche Schutzmaßnahmen.',
          en: 'Conduct a TIA and document supplementary measures.',
        },
        citations: [
          {
            documentId: contractId,
            page: 8,
            startChar: 1200,
            endChar: 1350,
            quotedText: 'Die Verarbeitung kann auch in Rechenzentren in den Vereinigten Staaten von Amerika erfolgen.',
            quoteHash: 'ghi789',
          },
        ],
        affectedRequirement: 'Art. 44-49 DSGVO, Schrems II',
        triggeredControls: ['VND-TRF-01', 'VND-TRF-03'],
        status: 'OPEN',
        createdAt: new Date(),
        updatedAt: new Date(),
      },
    ]

    // Calculate compliance score based on findings
    const okFindings = mockFindings.filter((f) => f.type === 'OK').length
    const totalChecks = mockFindings.length + 5 // Assume 5 additional checks passed
    const complianceScore = Math.round((okFindings / totalChecks) * 100 + 60) // Base score + passed checks

    return NextResponse.json({
      success: true,
      data: {
        contractId,
        findings: mockFindings,
        complianceScore: Math.min(100, complianceScore),
        reviewCompletedAt: new Date().toISOString(),
        topRisks: [
          { de: 'Meldefrist für Datenpannen zu lang', en: 'Data breach notification deadline too long' },
          { de: 'Fehlende TIA für USA-Transfer', en: 'Missing TIA for USA transfer' },
        ],
        requiredActions: [
          { de: 'Meldefrist auf 24-48h verkürzen', en: 'Reduce notification deadline to 24-48h' },
          { de: 'TIA für USA-Transfer durchführen', en: 'Conduct TIA for USA transfer' },
        ],
        source: 'mock',
      },
      timestamp: new Date().toISOString(),
    })
  } catch (error) {
    console.error('Error reviewing contract:', error)
    return NextResponse.json(
      { success: false, error: 'Failed to review contract' },
      { status: 500 }
    )
  }
}

/**
 * GET /api/sdk/v1/vendor-compliance/contracts/[id]/review
 *
 * Get existing review results
 */
export async function GET(
  request: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    const { id: contractId } = await params

    // In production, fetch from database
    return NextResponse.json({
      success: true,
      data: {
        contractId,
        findings: [],
        complianceScore: null,
        reviewStatus: 'PENDING',
      },
      timestamp: new Date().toISOString(),
    })
  } catch (error) {
    console.error('Error fetching review:', error)
    return NextResponse.json(
      { success: false, error: 'Failed to fetch review' },
      { status: 500 }
    )
  }
}
