#!/usr/bin/env php
<?php
declare(strict_types=1);

/**
 * Import graph_session NDJSON directly into graph_sessions (no HTTP).
 * Usage: php scripts/bulk_import_graph_sessions.php --file=/tmp/fake_graph_100dev.ndjson
 */
$opts = getopt('', ['file::', 'limit::']);
$file = $opts['file'] ?? '/tmp/fake_graph_sessions.ndjson';
$limit = isset($opts['limit']) ? max(0, (int) $opts['limit']) : 0;

if (!is_readable($file)) {
    fwrite(STDERR, "File not found: $file\n");
    exit(1);
}

require_once __DIR__ . '/../src/bootstrap.php';

$lines = file($file, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES) ?: [];
$ok = 0;
$fail = 0;
foreach ($lines as $i => $line) {
    if ($limit > 0 && $i >= $limit) {
        break;
    }
    $payload = json_decode($line, true);
    if (!is_array($payload)) {
        $fail++;
        continue;
    }
    try {
        GraphRepository::insertSession($payload);
        $ok++;
    } catch (Throwable $e) {
        $fail++;
        fwrite(STDERR, 'FAIL line ' . ($i + 1) . ': ' . $e->getMessage() . "\n");
    }
}

echo "Imported ok=$ok fail=$fail total=" . count($lines) . "\n";
exit($fail > 0 ? 1 : 0);
