<?php
/**
 * Contract Chat API — Gemini-powered Q&A against CFD documents.
 * Supports multiple documents: L48 contract, Operations Manual, Procedures Manual.
 */
require_once __DIR__ . '/../config/auth.php';
$user = requireLogin();

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    jsonResponse(['error' => 'POST only'], 405);
}

validateCsrf();

$input = json_decode(file_get_contents('php://input'), true);
$question = trim($input['question'] ?? '');
$history = $input['history'] ?? [];
$document = $input['document'] ?? 'l48-contract';
$compareMode = !empty($input['compare']);
$compareDocs = $input['compare'] ?? [];

if ($question === '') {
    jsonResponse(['error' => 'No question provided'], 400);
}

$apiKey = env('GOOGLE_GEMINI_API_KEY', '');
if (!$apiKey) {
    jsonResponse(['error' => 'Gemini API key not configured'], 500);
}

// Document configs
$documents = [
    'l48-contract' => [
        'file' => __DIR__ . '/../assets/data/l48-contract.txt',
        'name' => 'Local 48 Contract (2023-2026)',
        'prompt' => 'You are an expert labor relations analyst specializing in the Cincinnati Fire Fighters Union Local 48 contract (2023-2026 Labor-Management Agreement between the City of Cincinnati and IAFF Local 48).',
    ],
    'operations' => [
        'file' => __DIR__ . '/../assets/data/operations-manual.txt',
        'name' => 'CFD Operations Manual (08-09)',
        'prompt' => 'You are an expert fire department operations analyst specializing in the Cincinnati Fire Department Operations Manual. This manual contains standard operating procedures for emergency response, incident command, structure fires, hazmat, EMS, and all field operations.',
    ],
    'procedures' => [
        'file' => __DIR__ . '/../assets/data/procedures-manual.txt',
        'name' => 'CFD Policies & Procedures Manual',
        'prompt' => 'You are an expert fire department policy analyst specializing in the Cincinnati Fire Department Policies and Procedures Manual. This manual covers administration, vehicles, uniforms, personnel, training, facilities, fire prevention, and all departmental policies.',
    ],
];

// ─── Compare Mode ───────────────────────────────────
if ($compareMode && is_array($compareDocs) && count($compareDocs) >= 2) {
    $docTexts = '';
    $docNames = [];
    foreach ($compareDocs as $docId) {
        if (!isset($documents[$docId])) continue;
        $d = $documents[$docId];
        if (!file_exists($d['file'])) continue;
        $docTexts .= "\n\n=== DOCUMENT: {$d['name']} ===\n" . file_get_contents($d['file']) . "\n=== END {$d['name']} ===\n";
        $docNames[] = $d['name'];
    }

    $systemPrompt = "You are an expert labor relations and fire department policy analyst for the Cincinnati Fire Department. You have been given MULTIPLE documents to compare and cross-reference.

The documents loaded are: " . implode(', ', $docNames) . "

When answering comparison questions:

1. ALWAYS prefix every citation with the document tag in square brackets: [L48], [OPS], or [PROC]. For example: [L48] Article 37, Section 37.1 states (quoted text) or [OPS] SOP 204.01 states (quoted text)
2. When language differs between documents, quote BOTH versions side by side with their document tags
3. Highlight conflicts, gaps, or inconsistencies between the documents
4. Note when one document is silent on a topic that another addresses
5. Use clear headers to organize your response by document
6. If policies align, confirm that explicitly with citations from each
7. Use bullet point comparisons, NOT markdown tables (no pipe syntax). Use bold text for headers, not # markdown headers. Quote contract language in double quotes, NOT blockquote markers
8. The document tags are: [L48] = Local 48 Contract, [OPS] = CFD Operations Manual, [PROC] = CFD Policies & Procedures Manual

FULL DOCUMENT TEXTS:
{$docTexts}";

    $modelLabel = 'compare: ' . implode(' + ', $docNames);
} else {
    // ─── Single Document Mode ───────────────────────────
    if (!isset($documents[$document])) {
        jsonResponse(['error' => 'Unknown document'], 400);
    }

    $doc = $documents[$document];
    if (!file_exists($doc['file'])) {
        jsonResponse(['error' => 'Document file not found'], 500);
    }
    $docText = file_get_contents($doc['file']);

    $systemPrompt = $doc['prompt'] . "

You have the COMPLETE document text below. When answering questions:

1. ALWAYS cite specific section numbers, policy numbers, or article references when applicable
2. Quote exact language from the document using quotation marks — do NOT use > blockquote markdown
3. If a question involves a scenario, analyze it against ALL relevant provisions
4. If the document is silent on a topic, say so clearly
5. Use clear, professional language suitable for a Fire Chief or department officer
6. Use **bold** for headers and emphasis. Use bullet points (- ) for lists. Do NOT use # or ## or ### or #### markdown headers
7. If multiple sections apply, list all of them
8. Do NOT use markdown table syntax (|). Use bullet points or plain text comparisons instead
9. Keep formatting clean — use bold text, quoted text in double-quotes, and bullet points only
" . '10. IMPORTANT: When you present numerical data (salaries, rates, comparisons, counts), you MUST include a chart directive on its own line using this exact format:

[CHART:bar {"title":"My Title","labels":["A","B","C"],"datasets":[{"name":"Data","values":[10,20,30]}]}]

Chart types: bar, line, pie, radar. Keep arrays 3-10 items. The interface renders these as interactive ECharts. ALWAYS include a chart when showing salary data, rate comparisons, or any numerical breakdown. Put the chart AFTER your text explanation.' . "


FULL DOCUMENT TEXT ({$doc['name']}):
---
{$docText}
---";

    $modelLabel = $doc['name'];
}

$contents = [];
$contents[] = ['role' => 'user', 'parts' => [['text' => $systemPrompt]]];
$initResponse = $compareMode
    ? "I have loaded all selected documents and I'm ready to compare and cross-reference them. Ask me about conflicts, differences, or how policies align across the documents."
    : "I have read the complete {$modelLabel}. I'm ready to answer questions with specific citations. What would you like to know?";
$contents[] = ['role' => 'model', 'parts' => [['text' => $initResponse]]];

foreach ($history as $msg) {
    $contents[] = [
        'role' => $msg['role'] === 'user' ? 'user' : 'model',
        'parts' => [['text' => $msg['text']]]
    ];
}

$contents[] = ['role' => 'user', 'parts' => [['text' => $question]]];

$url = "https://generativelanguage.googleapis.com/v1beta/models/gemini-3.1-pro-preview:generateContent?key={$apiKey}";

$payload = json_encode([
    'contents' => $contents,
    'generationConfig' => [
        'temperature' => 0.3,
        'maxOutputTokens' => 4096,
        'topP' => 0.8,
    ]
]);

$ch = curl_init($url);
curl_setopt_array($ch, [
    CURLOPT_POST           => true,
    CURLOPT_POSTFIELDS     => $payload,
    CURLOPT_HTTPHEADER     => ['Content-Type: application/json'],
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_TIMEOUT        => 90,
    CURLOPT_SSL_VERIFYPEER => false,
]);

$response = curl_exec($ch);
$error = curl_error($ch);
curl_close($ch);

if ($error) {
    jsonResponse(['error' => 'Gemini API error: ' . $error], 502);
}

$data = json_decode($response, true);

if (!$data || isset($data['error'])) {
    $errMsg = $data['error']['message'] ?? 'Unknown Gemini error';
    jsonResponse(['error' => $errMsg], 502);
}

$answer = $data['candidates'][0]['content']['parts'][0]['text'] ?? 'No response generated.';

auditLog('contract_chat', $user['id'], "[{$document}] " . substr($question, 0, 200));

jsonResponse([
    'answer'   => $answer,
    'document' => $document,
    'model'    => 'gemini-3.1-pro-preview',
    'tokens'   => $data['usageMetadata'] ?? null,
]);
