#!/usr/bin/env php
<?php
/**
 * Ingest roadmap tasks as tickets tagged 20260604 (filter in Tickets UI).
 *
 * Usage:
 *   php scripts/ingest_roadmap_tickets_20260604.php [--url=BASE] [--owner=admin] [--dry-run]
 */
declare(strict_types=1);

$opts = getopt('', ['url::', 'owner::', 'dry-run']);
$base = rtrim($opts['url'] ?? 'https://apps.f0xx.org/app/androidcast_project/crashes', '/');
$owner = $opts['owner'] ?? 'admin';
$dryRun = isset($opts['dry-run']);
$uploadUrl = $base . '/api/ticket_upload.php';

/** @return list<array{id:string,label:string,bg:string}> */
function roadmap_tags(string $status): array {
    $statusMap = [
        'open' => ['id' => 'open', 'label' => 'open', 'bg' => '#22c55e'],
        'in-progress' => ['id' => 'in-progress', 'label' => 'in progress', 'bg' => '#3b82f6'],
        'closed' => ['id' => 'closed', 'label' => 'closed', 'bg' => '#6b7280'],
    ];
    return [
        ['id' => 'ticket', 'label' => 'ticket', 'bg' => '#6366f1'],
        ['id' => '20260604', 'label' => '20260604', 'bg' => '#0ea5e9'],
        $statusMap[$status] ?? $statusMap['open'],
    ];
}

/** title + body are the same description text */
$tasks = [
    ['key' => 'bug-ticket-detail-500', 'status' => 'closed', 'text' => 'ISSUE: Ticket detail page HTTP 500 (?view=ticket&id=N). Fix recursion in comment/attachment loaders when rendering detail.'],
    ['key' => '8', 'status' => 'closed', 'text' => 'COMPLETED: Orchestration branch feature/20260527_orchestration — merged to next; work lives under orchestration/; close/delete branch.'],
    ['key' => '1', 'status' => 'open', 'text' => 'BE/builder deployment phases — dedicated services on BE; WIP verifying (Docker, out/builds, runner_script).'],
    ['key' => '2', 'status' => 'open', 'text' => 'OTA checks — part of builder/deploy path; verify artifacts and device OTA flow.'],
    ['key' => '3', 'status' => 'open', 'text' => 'Opus/Speex validation — E2E, encryption, FEC, NACK, negotiations; user and developer controls.'],
    ['key' => '4', 'status' => 'open', 'text' => 'Alpha: RSSH remote access (prod/hidden, no VPN) — BE bastion + Android reverse SSH client; WG v1 lab only. Opus/Speex JNI sinks TODO.'],
    ['key' => 'auth-2fa', 'status' => 'open', 'text' => 'Alpha: registration + email verify + TOTP 2FA — mobile-friendly; depends on email DNS/SMTP. See docs/20260607-2FA-email-mobile-auth-flow.md.'],
    ['key' => 'email-dns', 'status' => 'open', 'text' => 'Alpha: email infra — info@/admin@/root@ @ apps.f0xx.org forward to Gmail; SPF/DKIM/DMARC. Blocks auth mail.'],
    ['key' => '5', 'status' => 'open', 'text' => 'Data visualization / graphs — WIP; issues found on drill-down and layout.'],
    ['key' => '5.1', 'status' => 'open', 'text' => 'ISSUE 5.1: Graph brick click must open full-browser detailed chart (axis, legend, hover per point like Java visualizer).'],
    ['key' => '5.2', 'status' => 'open', 'text' => 'REQUIREMENT 5.2: All graph preview bricks clickable; Columns combo (1/2/4) after Window default 2; grid uses full width.'],
    ['key' => '5.3', 'status' => 'closed', 'text' => 'ISSUE 5.3: Remove Direct DB metrics / graph_upload / graphs.php footnote from graphs page.'],
    ['key' => '6', 'status' => 'open', 'text' => 'Landing page checks, fixes, improvements — hub, styling, integration with dashboards.'],
    ['key' => '6.1', 'status' => 'open', 'text' => 'Landing 6.1: Hub dashboards for graphs, builder, remote access — partially done.'],
    ['key' => '6.1.1', 'status' => 'closed', 'text' => 'ISSUE 6.1.1: Remote access / graphs quick links — shell nav icons and 8px spacing.'],
    ['key' => '6.1.2', 'status' => 'closed', 'text' => 'ISSUE 6.1.2: Remove device poll / heartbeat dev footnote from Remote access page.'],
    ['key' => '6.2', 'status' => 'open', 'text' => 'Landing 6.2: Globe/earth animations — choose base on next; branch cleanup (3d_earth vs 20260531_globe_animation); clock/footer styling.'],
    ['key' => '6.3', 'status' => 'open', 'text' => 'Landing 6.3: Mobile device validations (mobile chrome) — LOW priority.'],
    ['key' => '7', 'status' => 'open', 'text' => 'BE roles RBAC — admin/root, slug admins, privilege sets; finish after related pages stable.'],
    ['key' => 'net-slowness', 'status' => 'open', 'text' => 'ISSUE: Sporadic FE/BE slowness (SSH, sshfs, web) — WAN/modem queueing suspected; investigate bufferbloat and paths.'],
];

$device = [
    'manufacturer' => 'roadmap',
    'model' => 'planning',
    'sdk_int' => 34,
    'release' => '14',
];
$app = ['package' => 'com.foxx.androidcast', 'version_name' => 'roadmap', 'version_code' => 1];
$now = (int) round(microtime(true) * 1000);
$ok = 0;
$fail = 0;

foreach ($tasks as $task) {
    $text = trim($task['text']);
    $key = $task['key'];
    $status = $task['status'];
    $payload = [
        'schema_version' => 1,
        'ingest_kind' => 'ticket',
        'ticket_id' => 'roadmap-20260604-' . preg_replace('/[^a-z0-9.-]+/i', '-', $key),
        'title' => mb_substr($text, 0, 256),
        'brief' => mb_substr($text, 0, 512),
        'body' => $text,
        'opened_at_epoch_ms' => $now,
        'rating' => $status === 'closed' ? 1 : 3,
        'owner' => $owner,
        'tags' => roadmap_tags($status),
        'device' => $device,
        'app' => $app,
    ];
    $json = json_encode($payload, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
    if ($dryRun) {
        echo "DRY {$key} [{$status}]\n";
        $ok++;
        continue;
    }
    $ctx = stream_context_create([
        'http' => [
            'method' => 'POST',
            'header' => "Content-Type: application/json\r\n",
            'content' => $json,
            'ignore_errors' => true,
        ],
    ]);
    $resp = @file_get_contents($uploadUrl, 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 === 409) {
        echo ($code === 409 ? 'DUP ' : 'OK  ') . "{$key}\n";
        $ok++;
    } else {
        echo "FAIL {$key} HTTP {$code} — {$resp}\n";
        $fail++;
    }
}

echo "Done: ok={$ok} fail={$fail}\n";
exit($fail > 0 ? 1 : 0);
