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

$opts = getopt('', ['count::', 'days::', 'out::', 'company::', 'user::']);
$count = max(10, (int) ($opts['count'] ?? 180));
$days = max(1, (int) ($opts['days'] ?? 14));
$out = $opts['out'] ?? '/tmp/fake_graph_sessions.ndjson';
$companyId = (int) ($opts['company'] ?? 1);
$userId = (int) ($opts['user'] ?? 1);

$nowMs = (int) round(microtime(true) * 1000);
$startFloorMs = $nowMs - ($days * 86400 * 1000);
$transports = ['wifi', 'cellular', 'ethernet'];
$installs = ['direct', 'play_store', 'mdm', 'partner'];
$ntp = ['device', 'backend', 'pool.ntp.org'];

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

for ($i = 0; $i < $count; $i++) {
    $start = random_int($startFloorMs, $nowMs - 120000);
    $duration = random_int(120, 9000);
    $end = $start + ($duration * 1000);
    $payload = [
        'schema_version' => 1,
        'ingest_kind' => 'graph_session',
        'session_id' => 'fake-' . gmdate('Ymd', (int) ($start / 1000)) . '-' . substr(sha1((string) ($start . ':' . $i)), 0, 12),
        'company_id' => $companyId,
        'user_id' => $userId,
        'device_id' => 'fake-dev-' . ($i % 40),
        'app_version' => '0.1.' . ($i % 5),
        'sdk_int' => 29 + ($i % 6),
        'started_at_epoch_ms' => $start,
        'ended_at_epoch_ms' => $end,
        'duration_s' => $duration,
        'completed' => ($i % 17 !== 0),
        'direction' => ($i % 3 === 0) ? 'receiver' : 'sender',
        'transport' => $transports[array_rand($transports)],
        'avg_kbps' => random_int(640, 12000),
        'recv_kbps' => random_int(200, 4000),
        'packet_loss_pct' => round(mt_rand(0, 600) / 100, 2),
        'ntp_source' => $ntp[array_rand($ntp)],
        'ntp_correction_s' => random_int(0, 8),
        'install_source' => $installs[array_rand($installs)],
        'meta' => ['fake' => true, 'seed' => $i],
    ];
    fwrite($fh, json_encode($payload, JSON_UNESCAPED_SLASHES) . "\n");
}
fclose($fh);
echo "Generated $count rows into $out\n";
