<?php
declare(strict_types=1);

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

dbnToolsRequireMethod('POST');
dbnToolsRequireAuth();
$input = dbnToolsJsonInput(1500000);
$language = dbnToolsNormalizeLanguage($input['language'] ?? 'en');
$_validEngines  = ['nova_lite', 'azure_mini', 'azure_full', 'claude_haiku', 'claude_sonnet'];
$_requestedEngine = in_array((string)($input['engine'] ?? ''), $_validEngines, true)
    ? (string)$input['engine'] : 'azure_mini';

$start = microtime(true);

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

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

    // Optional: prepend the user's case-context chunks so the timeline includes events
    // referenced in their uploaded case documents.
    $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']);

    $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);
    $engine            = (string)$timelineRoute['effective_engine'];

    $result = (new DbnLegalToolsService())->timeline($text, $language, $engine, $focus, $confidenceFilter, $includeRelative, $includeBackground, $userNotes, null);

    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'],
        ]);
        if ($balance >= 0 && !headers_sent()) {
            header('X-Credits-Remaining: ' . $balance);
        }
        $result['balance'] = $balance;
    }

    $latency = (int)round((microtime(true) - $start) * 1000);
    $result['ok'] = $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,
    ]);

    dbnToolsRespond($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,
    ]);
    dbnToolsError($e->getMessage(), $e->status, $e->errorCode, $e->extra);
} 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 error: ' . $e->getMessage());
    dbnToolsError('The tool could not complete this request.', 500, 'internal_error');
}
