<?php
declare(strict_types=1);

require_once __DIR__ . '/../../includes/bootstrap.php';
require_once __DIR__ . '/../../includes/CaseResults.php';

dbnToolsRequireMethod('GET');
dbnToolsRequireAuth();

if (!dbnToolsIsFreeTier()) {
    http_response_code(403);
    exit('Saved analyses are SSO-only.');
}

$userId = (int)($_SESSION['dbn_tools_sso_uid'] ?? 0);
$id     = (int)($_GET['id'] ?? 0);

if ($userId <= 0 || $id <= 0) {
    http_response_code(404);
    exit('Not found.');
}

$result = CaseResults::get($userId, $id);
if (!$result) {
    http_response_code(404);
    exit('Not found.');
}

$filename = sprintf(
    'dbn-%s-%d-%s.json',
    $result['tool'],
    $id,
    date('Ymd-His', strtotime((string)$result['created_at']))
);

header('Content-Type: application/json; charset=utf-8');
header('Content-Disposition: attachment; filename="' . $filename . '"');
header('Cache-Control: no-store');

echo json_encode([
    'id'                => (int)$result['id'],
    'tool'              => $result['tool'],
    'title'             => $result['title'],
    'created_at'        => $result['created_at'],
    'model'             => $result['model'],
    'latency_ms'        => $result['latency_ms'],
    'used_case_context' => (bool)$result['used_case_context'],
    'case_doc_ids'      => $result['case_doc_ids'],
    'input'             => $result['input_payload'],
    'output'            => $result['output_payload'],
], JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
