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

$opts = getopt('', ['file::', 'url::', 'dry-run']);
$file = $opts['file'] ?? '/tmp/fake_graph_sessions.ndjson';
$base = (string) ($opts['url'] ?? 'https://apps.f0xx.org/app/androidcast_project/graphs');
if ($base === '' || $base === '1') {
    $base = 'https://apps.f0xx.org/app/androidcast_project/graphs';
}
$base = rtrim($base, '/');
$dryRun = isset($opts['dry-run']);
$api = $base . '/api/graph_upload.php';

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

$lines = file($file, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES) ?: [];
$ok = 0;
$fail = 0;
foreach ($lines as $i => $line) {
    $payload = json_decode($line, true);
    if (!is_array($payload)) {
        $fail++;
        continue;
    }
    if ($dryRun) {
        $ok++;
        continue;
    }
    $ctx = stream_context_create([
        'http' => [
            'method' => 'POST',
            'header' => "Content-Type: application/json\r\n",
            'content' => json_encode($payload, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE),
            'ignore_errors' => true,
            'timeout' => 20,
        ],
    ]);
    $resp = @file_get_contents($api, false, $ctx);
    $code = 0;
    if (isset($http_response_header[0]) && preg_match('/\s(\d{3})\s/', $http_response_header[0], $m)) {
        $code = (int) $m[1];
    }
    if ($code >= 200 && $code < 300) {
        $ok++;
    } else {
        $fail++;
        fwrite(STDERR, "FAIL line " . ($i + 1) . " http=$code resp=$resp\n");
    }
}

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