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

$opts = getopt('', ['count::', 'days::', 'out::', 'company::', 'user::', 'devices::', 'per-device::']);
$devices = max(1, (int) ($opts['devices'] ?? 0));
$perDevice = max(1, (int) ($opts['per-device'] ?? 5));
$count = isset($opts['count']) ? max(1, (int) $opts['count']) : 0;
if ($count <= 0) {
    $count = $devices > 0 ? $devices * $perDevice : 180;
}
$days = max(1, (int) ($opts['days'] ?? 30));
$out = $opts['out'] ?? '/tmp/fake_graph_sessions.ndjson';
$companyId = (int) ($opts['company'] ?? 1);
$userId = (int) ($opts['user'] ?? 1);
if ($devices <= 0) {
    $devices = max(1, min(40, (int) ceil($count / max(1, $perDevice))));
}

$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' => 'grab-stats-dev-' . str_pad((string) ($i % $devices), 3, '0', STR_PAD_LEFT),
        '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,
            'grab_session_stats' => true,
            'simulated' => 'bulk-100-devices',
        ],
    ];
    fwrite($fh, json_encode($payload, JSON_UNESCAPED_SLASHES) . "\n");
}
fclose($fh);
echo "Generated $count rows ($devices devices, ~" . (int) ceil($count / $devices) . " sessions/device, {$days}d window) into $out\n";
