<?php
declare(strict_types=1);

if (PHP_SAPI !== 'cli') {
  http_response_code(404);
  exit;
}

require_once __DIR__ . '/../.lib/api/bootstrap.php';
require_once __DIR__ . '/../.lib/api/core.php';

$country = 'england';
$sourceUrl = 'https://football-logos.cc/' . $country . '/';
$imageBase = 'https://assets.football-logos.cc/logos/' . $country . '/128x128/';
$targetDir = YSP_CODE_ROOT . '/assets/logos/' . $country;

$aliases = [
  'carlisle-united' => 'carlisle',
  'fc-halifax-town' => 'halifax-town',
  'hartlepool-united' => 'hartlepool',
  'scunthorpe-united' => 'scunthorpe',
  'southend-united' => 'southend',
  'yeovil-town' => 'yeovil',
];

function logo_fetch(string $url): string {
  $context = stream_context_create([
    'http' => [
      'timeout' => 25,
      'header' => "User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 Chrome/126 Safari/537.36\r\nReferer: https://football-logos.cc/england/\r\n",
    ],
  ]);
  $data = @file_get_contents($url, false, $context);
  if (!is_string($data) || $data === '') {
    fwrite(STDERR, "Could not fetch $url\n");
    exit(1);
  }
  return $data;
}

function logo_parse_catalog(string $html): array {
  $parts = preg_split('~<div class="group [^>]+ data-logo-downloads ~', $html);
  $logos = [];
  foreach (array_slice(is_array($parts) ? $parts : [], 1) as $chunk) {
    if (!preg_match('~data-logo-id="([^"]+)"~', $chunk, $id)) continue;
    if (!preg_match('~<h3[^>]*>\s*([^<]+?)\s*</h3>~s', $chunk, $name)) continue;
    if (!preg_match('~<option value="128::([a-f0-9]+)"~i', $chunk, $hash)) continue;
    $slug = (string)$id[1];
    $logos[$slug] = [
      'slug' => $slug,
      'name' => trim(html_entity_decode((string)$name[1], ENT_QUOTES | ENT_HTML5)),
      'hash' => strtolower((string)$hash[1]),
    ];
  }
  return $logos;
}

function logo_safe_png(string $bytes): bool {
  return strncmp($bytes, "\x89PNG\r\n\x1a\n", 8) === 0;
}

if (!is_dir($targetDir) && !@mkdir($targetDir, 0775, true)) {
  fwrite(STDERR, "Could not create $targetDir\n");
  exit(1);
}

$catalog = logo_parse_catalog(logo_fetch($sourceUrl));
$out = [];
$missing = [];

foreach (teams() as $team) {
  $teamId = (string)($team['id'] ?? '');
  if ($teamId === '') continue;
  $slug = $aliases[$teamId] ?? $teamId;
  if (empty($catalog[$slug])) {
    $missing[] = $teamId;
    continue;
  }
  $logo = $catalog[$slug];
  $fileName = $teamId . '.png';
  $localPath = $targetDir . '/' . $fileName;
  $url = $imageBase . $logo['slug'] . '.' . $logo['hash'] . '.png';
  $bytes = logo_fetch($url);
  if (!logo_safe_png($bytes)) {
    fwrite(STDERR, "Downloaded file was not PNG: $url\n");
    exit(1);
  }
  if (@file_put_contents($localPath, $bytes, LOCK_EX) === false) {
    fwrite(STDERR, "Could not write $localPath\n");
    exit(1);
  }
  @chmod($localPath, 0644);
  $out[$teamId] = [
    'path' => 'assets/logos/' . $country . '/' . $fileName . '?v=' . $logo['hash'],
    'source' => $sourceUrl . $logo['slug'] . '/',
    'sourceName' => $logo['name'],
  ];
}

ksort($out);
$json = json_encode($out, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
if (!is_string($json) || @file_put_contents(TEAM_LOGOS_FILE, $json . "\n", LOCK_EX) === false) {
  fwrite(STDERR, "Could not write " . TEAM_LOGOS_FILE . "\n");
  exit(1);
}
@chmod(TEAM_LOGOS_FILE, 0644);

echo 'Imported ' . count($out) . " logos\n";
if ($missing) {
  echo 'Missing: ' . implode(', ', $missing) . "\n";
}
