#!/usr/bin/env php
<?php
/**
 * Parse tmp/alpha_smoke_round1.txt and POST tickets to ticket_upload.php.
 *
 * Usage:
 *   php scripts/ingest_alpha_smoke_tickets.php [--file=path] [--url=BASE] [--owner=admin] [--dry-run]
 *
 * Default input: <repo>/tmp/alpha_smoke_round1.txt (project root, not examples/).
 */
declare(strict_types=1);

// scripts → backend → crash_reporter → examples → repo root
$repoRoot = dirname(__DIR__, 4);
$defaultFile = $repoRoot . '/tmp/alpha_smoke_round1.txt';
$opts = getopt('', ['file::', 'url::', 'owner::', 'dry-run', 'device::', 'app-version::']);

$file = $opts['file'] ?? $defaultFile;
$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';

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

$lines = file($file, FILE_IGNORE_NEW_LINES);
$rows = [];
foreach ($lines as $line) {
    $line = trim($line);
    if ($line === '' || str_starts_with($line, 'block |')) {
        continue;
    }
    $parts = array_map('trim', explode('|', $line, 3));
    if (count($parts) < 3) {
        continue;
    }
    [$block, $expected, $actual] = $parts;
    $rows[] = compact('block', 'expected', 'actual');
}

$device = [
    'manufacturer' => 'DOOGEE',
    'brand' => 'DOOGEE',
    'model' => $opts['device'] ?? 'BL6000 Pro',
    'sdk_int' => 29,
    'release' => '10',
    'abis' => ['arm64-v8a', 'armeabi-v7a'],
];
$app = [
    'package' => 'com.foxx.androidcast',
    'version_name' => $opts['app-version'] ?? '0.1.0-alpha',
    'version_code' => 1,
];

function classify_row(array $row): array {
    $actual = $row['actual'];
    $pass = (bool) preg_match('/^\s*pass\b/i', $actual) && !preg_match('/\bNOK\b/i', $actual);
    $needsTicket = !$pass
        || preg_match('/needs review|remark|poor|low-res|frame drop|lifecycle|VU-meter|laggy|wrong/i', $actual);
    if (!$needsTicket) {
        return ['skip' => true];
    }
    $status = 'open';
    $rating = 3;
    if (preg_match('/\bNOK\b/i', $actual)) {
        $status = 'urgent';
        $rating = 4;
    } elseif ($pass) {
        $status = 'confirmed';
        $rating = 2;
    }
    if (preg_match('/needs review/i', $actual)) {
        $status = 'in-progress';
    }
    return ['skip' => false, 'status' => $status, 'rating' => $rating];
}

function ticket_tags(string $status): array {
  $map = [
      'open' => ['id' => 'open', 'label' => 'open', 'bg' => '#22c55e'],
      'in-progress' => ['id' => 'in-progress', 'label' => 'in progress', 'bg' => '#3b82f6'],
      'confirmed' => ['id' => 'confirmed', 'label' => 'confirmed', 'bg' => '#047857'],
      'urgent' => ['id' => 'urgent', 'label' => 'urgent', 'bg' => '#dc2626'],
      'closed' => ['id' => 'closed', 'label' => 'closed', 'bg' => '#6b7280'],
  ];
  $tags = [
      ['id' => 'ticket', 'label' => 'ticket', 'bg' => '#6366f1'],
      ['id' => 'alpha-smoke', 'label' => 'alpha-smoke', 'bg' => '#8b5cf6'],
      $map[$status] ?? $map['open'],
  ];
  return $tags;
}

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

foreach ($rows as $row) {
    $class = classify_row($row);
    if (!empty($class['skip'])) {
        $skip++;
        continue;
    }
    $block = $row['block'];
    $title = 'Alpha smoke ' . $block . ': ' . mb_substr($row['expected'], 0, 80);
    $brief = mb_substr($row['actual'], 0, 240);
    $body = "Block: {$block}\n\nExpected:\n{$row['expected']}\n\nActual:\n{$row['actual']}\n\nSource: alpha_smoke_round1.txt";
    $payload = [
        'schema_version' => 1,
        'ingest_kind' => 'ticket',
        'ticket_id' => 'alpha-smoke-' . strtolower($block) . '-' . substr(sha1($body), 0, 12),
        'title' => $title,
        'brief' => $brief,
        'body' => $body,
        'opened_at_epoch_ms' => $now,
        'rating' => $class['rating'],
        'owner' => $owner,
        'verified_by' => '',
        'tags' => ticket_tags($class['status']),
        'device' => $device,
        'app' => $app,
        'alpha_block' => $block,
        'source_file' => basename($file),
        'source_excerpt' => $body,
    ];
    $json = json_encode($payload, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
    if ($dryRun) {
        echo "DRY $block → {$payload['ticket_id']} [{$class['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) {
        echo "OK   $block\n";
        $ok++;
    } elseif ($code === 409) {
        echo "DUP  $block\n";
        $ok++;
    } else {
        echo "FAIL $block HTTP $code — $resp\n";
        $fail++;
    }
}

echo "Done: uploaded=$ok skipped=$skip failed=$fail\n";
exit($fail > 0 ? 1 : 0);
