<?php
declare(strict_types=1);
require_once __DIR__ . '/../../src/bootstrap.php';

$raw = file_get_contents('php://input');
if ($raw === false || $raw === '') {
    json_out(['ok' => false, 'error' => 'empty body'], 400);
}
$data = json_decode($raw, true);
if (!is_array($data)) {
    json_out(['ok' => false, 'error' => 'invalid json'], 400);
}
if ((int) ($data['schema_version'] ?? 0) !== 1) {
    json_out(['ok' => false, 'error' => 'unsupported schema_version'], 400);
}
if (($data['ingest_kind'] ?? 'graph_session') !== 'graph_session') {
    json_out(['ok' => false, 'error' => 'ingest_kind must be graph_session'], 400);
}

try {
    GraphRepository::insertSession($data);
    json_out(['ok' => true, 'session_id' => $data['session_id'] ?? null]);
} catch (InvalidArgumentException $e) {
    json_out(['ok' => false, 'error' => $e->getMessage()], 400);
} catch (Throwable $e) {
    error_log('graph upload: ' . $e->getMessage());
    $out = ['ok' => false, 'error' => 'store_failed'];
    if (cfg('debug')) {
        $out['hint'] = $e->getMessage();
    }
    json_out($out, 500);
}
