<?php
declare(strict_types=1);

require_once __DIR__ . '/../includes/LegalTools.php';
require_once __DIR__ . '/../includes/ToolModels.php';

dbnToolsRequireMethod('POST');
dbnToolsRequireAuth();

// Parse input and run credit pre-check BEFORE emitting SSE headers so that
// auth/credit errors can still return JSON (dbnToolsError / dbnToolsAbort).
$input    = dbnToolsJsonInput(1500000);
$language = dbnToolsNormalizeLanguage($input['language'] ?? 'en');

$_validEngines  = ['nova_lite', 'azure_mini', 'azure_full'];
$_requestedEngine = in_array((string)($input['engine'] ?? ''), $_validEngines, true)
    ? (string)$input['engine'] : 'azure_mini';

try {
    $text = dbnToolsInjectDocContent($input, dbnToolsString($input, 'text', ToolModels::TIMELINE_DEEP_MAX_CHARS, false));
    if (mb_strlen(trim($text), 'UTF-8') < 10) {
        dbnToolsError('Paste text, upload a file, or select a document before running.', 422, 'empty_text');
    }

    $ftUid = dbnToolsIsFreeTier() ? (int)($_SESSION['dbn_tools_sso_uid'] ?? 0) : 0;

    $useMyCase = !empty($input['use_my_case']);
    if ($useMyCase) {
        $caseBlock = dbnToolsCaseContext(true, $text, 5);
        if ($caseBlock !== '') {
            $text = $text . "\n\n" . $caseBlock;
        }
    }

    $timelineRoute = ToolModels::timelineRoute($ftUid, $_requestedEngine, $text);
    ToolModels::assertTimelineQuoteAccepted($timelineRoute, $input);
    $ftUid = dbnToolsFreeTierCheckAmount('timeline', (int)$timelineRoute['credits']);
} catch (DbnToolsHttpException $e) {
    dbnToolsError($e->getMessage(), $e->status, $e->errorCode, $e->extra);
} catch (Throwable $e) {
    error_log('timeline-stream preparation error: ' . $e->getMessage());
    dbnToolsError('The tool could not prepare this request.', 500, 'internal_error');
}

// Only switch to SSE mode once auth + credit checks pass.
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache, no-transform');
header('X-Accel-Buffering: no');
while (ob_get_level() > 0) ob_end_flush();
ob_implicit_flush(true);

function sseEmit(string $event, array $data): void
{
    echo "event: {$event}\n";
    echo 'data: ' . json_encode($data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) . "\n\n";
    if (function_exists('flush')) @flush();
}

$start = microtime(true);

try {
    $engine = (string)$timelineRoute['effective_engine'];
    if (!empty($timelineRoute['auto_upgraded_engine'])) {
        $label = match ($engine) {
            'azure_full' => 'Deep',
            'azure_mini' => 'Standard',
            default => 'Quick',
        };
        sseEmit('status', [
            'msg' => 'This input is ' . number_format((int)$timelineRoute['input_char_count']) . " characters, so Timeline is using {$label} for reliability.",
        ]);
    }
    if (!empty($timelineRoute['chunked_timeline'])) {
        sseEmit('status', [
            'msg' => 'Processing ' . (int)$timelineRoute['timeline_chunk_count'] . ' timeline chunk(s).',
        ]);
    }

    $validFocus = ['all', 'deadlines', 'hearings', 'cps'];
    $focus = in_array((string)($input['focus'] ?? ''), $validFocus, true)
        ? (string)$input['focus'] : 'all';

    $confidenceFilter = (string)($input['confidence_filter'] ?? '') === 'high_medium'
        ? 'high_medium' : 'all';

    $includeRelative   = ($input['include_relative']   ?? true) !== false;
    $includeBackground = ($input['include_background'] ?? true) !== false;
    $userNotes         = dbnToolsString($input, 'user_notes', 2000, false);

    $result = (new DbnLegalToolsService())->timeline(
        $text, $language, $engine, $focus, $confidenceFilter,
        $includeRelative, $includeBackground, $userNotes,
        fn(string $msg) => sseEmit('status', ['msg' => $msg])
    );

    $latency = (int)round((microtime(true) - $start) * 1000);

    if ($ftUid > 0) {
        $balance = dbnToolsFreeTierDeductAmount($ftUid, 'timeline', (int)$timelineRoute['credits'], [
            'requested_engine' => $timelineRoute['requested_engine'],
            'effective_engine' => $timelineRoute['effective_engine'],
            'auto_upgraded_engine' => $timelineRoute['auto_upgraded_engine'],
            'input_char_count' => $timelineRoute['input_char_count'],
        ]);
        $result['balance'] = $balance;
        if (!headers_sent()) {
            header('X-Credits-Remaining: ' . $balance);
        }
    }

    $result['ok']         = true;
    $result['latency_ms'] = $latency;
    $result['trace_metadata'] = array_merge($result['trace_metadata'] ?? [], [
        'requested_engine' => $timelineRoute['requested_engine'],
        'effective_engine' => $timelineRoute['effective_engine'],
        'auto_upgraded_engine' => $timelineRoute['auto_upgraded_engine'],
        'input_char_count' => $timelineRoute['input_char_count'],
        'engine_limit_chars' => $timelineRoute['engine_limit_chars'],
        'max_char_limit' => $timelineRoute['max_char_limit'],
        'chunked_timeline' => $timelineRoute['chunked_timeline'],
        'timeline_chunk_count' => $timelineRoute['timeline_chunk_count'],
        'estimated_credits' => $timelineRoute['estimated_credits'],
        'credits_charged' => $timelineRoute['credits'],
    ]);

    dbnToolsLogMetadata([
        'tool'         => 'timeline',
        'language'     => $language,
        'ok'           => true,
        'latency_ms'   => $latency,
        'chunk_count'  => (int)($result['trace_metadata']['chunk_count']  ?? 0),
        'source_count' => (int)($result['trace_metadata']['source_count'] ?? 0),
        'deployment'   => $result['trace_metadata']['deployment'] ?? null,
    ]);

    sseEmit('result', $result);

} catch (DbnToolsHttpException $e) {
    $latency = (int)round((microtime(true) - $start) * 1000);
    dbnToolsLogMetadata([
        'tool'       => 'timeline',
        'language'   => $language,
        'ok'         => false,
        'latency_ms' => $latency,
        'error_code' => $e->errorCode,
    ]);
    sseEmit('error', ['code' => $e->errorCode, 'message' => $e->getMessage()]);
} catch (Throwable $e) {
    $latency = (int)round((microtime(true) - $start) * 1000);
    dbnToolsLogMetadata([
        'tool'       => 'timeline',
        'language'   => $language,
        'ok'         => false,
        'latency_ms' => $latency,
        'error_code' => 'internal_error',
    ]);
    error_log('timeline-stream error: ' . $e->getMessage());
    sseEmit('error', ['code' => 'internal_error', 'message' => 'The tool could not complete this request.']);
}
