#!/usr/bin/env php
<?php
/**
 * Ingest 2026-06-08 priority renumber as tickets (tag 20260608).
 *
 * Usage:
 *   php scripts/ingest_priorities_20260608.php [--url=BASE] [--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';

function priority_tags(string $ownerTag): array {
    return [
        ['id' => 'ticket', 'label' => 'ticket', 'bg' => '#6366f1'],
        ['id' => '20260608', 'label' => '20260608', 'bg' => '#0ea5e9'],
        ['id' => 'open', 'label' => 'open', 'bg' => '#22c55e'],
        ['id' => $ownerTag, 'label' => $ownerTag, 'bg' => $ownerTag === 'dev' ? '#f59e0b' : '#3b82f6'],
    ];
}

$tasks = [
    ['key' => '0.1', 'owner' => 'agent', 'text' => 'P0 FR: Stream dump while casting — zip + meta.json + raw A/V; see docs/20260608_STREAM_DUMP_DEBUG.md. Cyclic with 6.6.'],
    ['key' => '1', 'owner' => 'agent', 'text' => 'P1 Graphs dashboard parent — fixes + FRs.'],
    ['key' => '1.1', 'owner' => 'agent', 'text' => 'P1.1 Graphs: all pending fixes (drill-down, perf, permalinks).'],
    ['key' => '1.2', 'owner' => 'agent', 'text' => 'P1.2 Graphs: all pending FRs (columns 1/2/4, full-width grid).'],
    ['key' => '2.1', 'owner' => 'dev', 'text' => 'P2.1 DEV: DNS MX/SPF/DKIM/DMARC for apps.f0xx.org — tmp/20260608_help_request.md'],
    ['key' => '2.2', 'owner' => 'dev', 'text' => 'P2.2 DEV: Email forward info@/admin@/root@ → Gmail.'],
    ['key' => '2.3', 'owner' => 'dev', 'text' => 'P2.3 DEV: Verify inbound mail to info@apps.f0xx.org.'],
    ['key' => '2.4', 'owner' => 'dev', 'text' => 'P2.4 DEV: Gmail filters / reply-as optional.'],
    ['key' => '2.5', 'owner' => 'agent', 'text' => 'P2.5 AGENT: BE outbound SMTP for verification emails (blocked on 2.1).'],
    ['key' => '3', 'owner' => 'agent', 'text' => 'P3 AGENT: Auth register + verify + TOTP + migration 008 — docs/20260607-2FA-email-mobile-auth-flow.md'],
    ['key' => '4', 'owner' => 'agent', 'text' => 'P4 AGENT: Reverse SSH alpha — replace WG for prod; mobile + BE; hidden no VPN.'],
    ['key' => '5.1', 'owner' => 'shared', 'text' => 'P5.1 OTA channel + artifacts — 50% dev / 50% agent.'],
    ['key' => '5.2', 'owner' => 'shared', 'text' => 'P5.2 Device crash/OTA URLs — 50% dev / 50% agent.'],
    ['key' => '5.3', 'owner' => 'agent', 'text' => 'P5.3 RSSH BE validation — depends on 4.x.'],
    ['key' => '5.4', 'owner' => 'agent', 'text' => 'P5.4 auth-2fa validation ALPHA G2–G6.'],
    ['key' => '5.5', 'owner' => 'agent', 'text' => 'P5.5 RBAC validation.'],
    ['key' => '6.1', 'owner' => 'dev', 'text' => 'P6.1 Opus/Speex E2E — dev + agent JNI.'],
    ['key' => '6.2', 'owner' => 'dev', 'text' => 'P6.2 LAN soak A/B/C.'],
    ['key' => '6.3', 'owner' => 'dev', 'text' => 'P6.3 App lifecycle notifications/recents.'],
    ['key' => '6.4', 'owner' => 'dev', 'text' => 'P6.4 Rotation + preview crash — cyclic with 6.3.'],
    ['key' => '6.5', 'owner' => 'dev', 'text' => 'P6.5 Audio lag — use 0.1 dumps for analysis.'],
    ['key' => '6.6', 'owner' => 'dev', 'text' => 'P6.6 Stream debug analysis — same as 0.1.'],
    ['key' => '9', 'owner' => 'agent', 'text' => 'P9 Landing hub — LOW priority.'],
    ['key' => '9.1', 'owner' => 'agent', 'text' => 'P9.1 Hub cards graphs/builder/RA.'],
    ['key' => '9.2', 'owner' => 'agent', 'text' => 'P9.2 Globe animation branch cleanup.'],
    ['key' => '9.3', 'owner' => 'agent', 'text' => 'P9.3 Mobile chrome validation LOW.'],
];

$now = (int) round(microtime(true) * 1000);
$ok = 0;
$fail = 0;

foreach ($tasks as $task) {
    $text = $task['text'];
    $ownerTag = $task['owner'];
    $payload = [
        'schema_version' => 1,
        'ingest_kind' => 'ticket',
        'ticket_id' => 'priority-20260608-' . preg_replace('/[^a-z0-9.-]+/i', '-', $task['key']),
        'title' => mb_substr($text, 0, 256),
        'brief' => mb_substr($text, 0, 512),
        'body' => $text . "\n\nRef: docs/20260608_ALPHA_PRIORITIES.md",
        'opened_at_epoch_ms' => $now,
        'rating' => 3,
        'owner' => $owner,
        'tags' => priority_tags($ownerTag),
        'device' => ['manufacturer' => 'roadmap', 'model' => 'priorities', 'sdk_int' => 34, 'release' => '14'],
        'app' => ['package' => 'com.foxx.androidcast', 'version_name' => 'roadmap', 'version_code' => 1],
    ];
    if ($dryRun) {
        echo "DRY {$task['key']} [{$ownerTag}]\n";
        $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,
        ],
    ]);
    $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  ') . "{$task['key']}\n";
        $ok++;
    } else {
        echo "FAIL {$task['key']} HTTP {$code} — {$resp}\n";
        $fail++;
    }
}

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