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

/** Convert graph_session NDJSON to MySQL bulk INSERT SQL. */
$opts = getopt('', ['file::', 'out::']);
$file = $opts['file'] ?? '/tmp/fake_graph_sessions.ndjson';
$out = $opts['out'] ?? '/tmp/fake_graph_sessions.sql';

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

function sqlQuote(?string $s): string {
    if ($s === null) {
        return 'NULL';
    }
    return "'" . str_replace(["\\", "'"], ["\\\\", "''"], $s) . "'";
}

$fh = fopen($out, 'wb');
if (!$fh) {
    fwrite(STDERR, "Cannot write $out\n");
    exit(1);
}
fwrite($fh, "SET NAMES utf8mb4;\nSTART TRANSACTION;\n");

$batch = [];
$batchSize = 50;
$total = 0;

foreach (file($file, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES) ?: [] as $line) {
    $p = json_decode($line, true);
    if (!is_array($p)) {
        continue;
    }
    $dir = strtolower((string) ($p['direction'] ?? 'sender'));
    if ($dir !== 'sender' && $dir !== 'receiver') {
        $dir = 'sender';
    }
    $completed = !empty($p['completed']) ? 1 : 0;
    $meta = isset($p['meta']) && is_array($p['meta'])
        ? json_encode($p['meta'], JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE)
        : null;
    $batch[] = '(' . implode(', ', [
        sqlQuote((string) ($p['session_id'] ?? '')),
        (int) ($p['company_id'] ?? 1),
        (int) ($p['user_id'] ?? 1),
        sqlQuote((string) ($p['device_id'] ?? '')),
        sqlQuote((string) ($p['app_version'] ?? '')),
        (int) ($p['sdk_int'] ?? 0),
        (int) ($p['started_at_epoch_ms'] ?? 0),
        (int) ($p['ended_at_epoch_ms'] ?? 0),
        (int) ($p['duration_s'] ?? 0),
        $completed,
        sqlQuote($dir),
        sqlQuote((string) ($p['transport'] ?? 'wifi')),
        (int) ($p['avg_kbps'] ?? 0),
        (int) ($p['recv_kbps'] ?? 0),
        number_format((float) ($p['packet_loss_pct'] ?? 0), 3, '.', ''),
        sqlQuote((string) ($p['ntp_source'] ?? 'device')),
        isset($p['ntp_correction_s']) ? (int) $p['ntp_correction_s'] : 'NULL',
        sqlQuote((string) ($p['install_source'] ?? 'direct')),
        $meta !== null ? sqlQuote($meta) : 'NULL',
    ]) . ')';
    $total++;
    if (count($batch) >= $batchSize) {
        fwrite($fh, "INSERT INTO graph_sessions\n");
        fwrite($fh, "  (session_id, company_id, user_id, device_id, app_version, sdk_int,\n");
        fwrite($fh, "   started_at_ms, ended_at_ms, duration_s, completed, direction, transport,\n");
        fwrite($fh, "   avg_kbps, recv_kbps, packet_loss_pct, ntp_source, ntp_correction_s, install_source, meta_json)\n");
        fwrite($fh, "VALUES\n  " . implode(",\n  ", $batch) . "\n");
        fwrite($fh, "ON DUPLICATE KEY UPDATE\n");
        fwrite($fh, "  ended_at_ms=VALUES(ended_at_ms), duration_s=VALUES(duration_s), completed=VALUES(completed),\n");
        fwrite($fh, "  avg_kbps=VALUES(avg_kbps), recv_kbps=VALUES(recv_kbps), packet_loss_pct=VALUES(packet_loss_pct),\n");
        fwrite($fh, "  meta_json=VALUES(meta_json);\n");
        $batch = [];
    }
}

if ($batch) {
    fwrite($fh, "INSERT INTO graph_sessions\n");
    fwrite($fh, "  (session_id, company_id, user_id, device_id, app_version, sdk_int,\n");
    fwrite($fh, "   started_at_ms, ended_at_ms, duration_s, completed, direction, transport,\n");
    fwrite($fh, "   avg_kbps, recv_kbps, packet_loss_pct, ntp_source, ntp_correction_s, install_source, meta_json)\n");
    fwrite($fh, "VALUES\n  " . implode(",\n  ", $batch) . "\n");
    fwrite($fh, "ON DUPLICATE KEY UPDATE\n");
    fwrite($fh, "  ended_at_ms=VALUES(ended_at_ms), duration_s=VALUES(duration_s), completed=VALUES(completed),\n");
    fwrite($fh, "  avg_kbps=VALUES(avg_kbps), recv_kbps=VALUES(recv_kbps), packet_loss_pct=VALUES(packet_loss_pct),\n");
    fwrite($fh, "  meta_json=VALUES(meta_json);\n");
}

fwrite($fh, "COMMIT;\n");
fclose($fh);
echo "Wrote $total rows to $out\n";
