<?php
declare(strict_types=1);

$root = dirname(__DIR__);
$namesFile = $root . '/.legacy-player-names.json';
$outFile = $root . '/.player-nationalities.json';

$teamUrls = [
  'afc_fylde' => 'https://www.transfermarkt.com/afc-fylde/startseite/verein/22672/saison_id/2026',
  'aldershot_town' => 'https://www.transfermarkt.com/aldershot-town/startseite/verein/3717/saison_id/2026',
  'altrincham' => 'https://www.transfermarkt.com/altrincham-fc/startseite/verein/2962/saison_id/2026',
  'barrow' => 'https://www.transfermarkt.com/afc-barrow/startseite/verein/6168/saison_id/2026',
  'boreham_wood' => 'https://www.transfermarkt.com/fc-boreham-wood/startseite/verein/3867/saison_id/2026',
  'boston_united' => 'https://www.transfermarkt.com/boston-united/startseite/verein/3489/saison_id/2026',
  'carlisle_united' => 'https://www.transfermarkt.com/carlisle-united/startseite/verein/1220/saison_id/2026',
  'eastleigh' => 'https://www.transfermarkt.com/eastleigh-fc/startseite/verein/10391/saison_id/2026',
  'fc_halifax_town' => 'https://www.transfermarkt.com/fc-halifax-town/startseite/verein/1127/saison_id/2026',
  'forest_green_rovers' => 'https://www.transfermarkt.com/forest-green-rovers/startseite/verein/3455/saison_id/2026',
  'gateshead' => 'https://www.transfermarkt.com/fc-gateshead/startseite/verein/3456/saison_id/2026',
  'harrogate_town' => 'https://www.transfermarkt.com/harrogate-town/startseite/verein/12020/saison_id/2026',
  'hartlepool_united' => 'https://www.transfermarkt.com/hartlepool-united/startseite/verein/2577/saison_id/2026',
  'hornchurch' => 'https://www.transfermarkt.com/afc-hornchurch/startseite/verein/3868/saison_id/2026',
  'kidderminster_harriers' => 'https://www.transfermarkt.com/kidderminster-harriers/startseite/verein/1195/saison_id/2026',
  'scunthorpe_united' => 'https://www.transfermarkt.com/scunthorpe-united/startseite/verein/2964/saison_id/2026',
  'solihull_moors' => 'https://www.transfermarkt.com/solihull-moors/startseite/verein/12335/saison_id/2026',
  'southend_united' => 'https://www.transfermarkt.com/southend-united/startseite/verein/2793/saison_id/2026',
  'sutton_united' => 'https://www.transfermarkt.com/sutton-united/startseite/verein/3052/saison_id/2026',
  'tamworth' => 'https://www.transfermarkt.com/tamworth-fc/startseite/verein/3539/saison_id/2026',
  'wealdstone' => 'https://www.transfermarkt.com/fc-wealdstone/startseite/verein/4117/saison_id/2026',
  'woking' => 'https://www.transfermarkt.com/fc-woking/startseite/verein/2796/saison_id/2026',
  'worthing' => 'https://www.transfermarkt.com/worthing-fc/startseite/verein/8123/saison_id/2026',
  'yeovil_town' => 'https://www.transfermarkt.com/yeovil-town/startseite/verein/972/saison_id/2026',
];

$countryCodeMap = [
  'afghanistan' => 'af',
  'albania' => 'al',
  'angola' => 'ao',
  'antigua and barbuda' => 'ag',
  'australia' => 'au',
  'belgium' => 'be',
  'belize' => 'bz',
  'bulgaria' => 'bg',
  'burundi' => 'bi',
  'cameroon' => 'cm',
  'colombia' => 'co',
  'congo' => 'cg',
  "cote d'ivoire" => 'ci',
  'cyprus' => 'cy',
  'dominica' => 'dm',
  'dr congo' => 'cd',
  'ecuador' => 'ec',
  'england' => 'gb-eng',
  'finland' => 'fi',
  'france' => 'fr',
  'ghana' => 'gh',
  'gibraltar' => 'gi',
  'greece' => 'gr',
  'grenada' => 'gd',
  'guyana' => 'gy',
  'india' => 'in',
  'ireland' => 'ie',
  'jamaica' => 'jm',
  'kenya' => 'ke',
  'kosovo' => 'xk',
  'latvia' => 'lv',
  'lebanon' => 'lb',
  'mali' => 'ml',
  'malta' => 'mt',
  'montserrat' => 'ms',
  'nepal' => 'np',
  'netherlands' => 'nl',
  'new zealand' => 'nz',
  'nigeria' => 'ng',
  'northern ireland' => 'gb-nir',
  'pakistan' => 'pk',
  'poland' => 'pl',
  'scotland' => 'gb-sct',
  'somalia' => 'so',
  'south africa' => 'za',
  'spain' => 'es',
  'st. lucia' => 'lc',
  'st. vincent & grenadinen' => 'vc',
  'suriname' => 'sr',
  'turkey' => 'tr',
  'turkiye' => 'tr',
  'uganda' => 'ug',
  'united states' => 'us',
  'wales' => 'gb-wls',
  'zimbabwe' => 'zw',
];

function clean_text(string $value): string {
  $value = html_entity_decode($value, ENT_QUOTES | ENT_HTML5, 'UTF-8');
  $value = str_replace(["\xc2\xa0", "\u{00a0}"], ' ', $value);
  return trim((string)preg_replace('/\s+/u', ' ', $value));
}

function name_key(string $value): string {
  $value = strtolower(clean_text($value));
  $value = str_replace(['’', '`'], "'", $value);
  return (string)preg_replace('/[^a-z0-9]+/u', '', $value);
}

function country_code(string $country, array $countryCodeMap): string {
  $key = strtolower(trim(str_replace('Türkiye', 'Turkiye', $country)));
  return $countryCodeMap[$key] ?? '';
}

function fetch_transfermarkt(string $url): string {
  $context = stream_context_create([
    'http' => [
      'header' => "User-Agent: Mozilla/5.0\r\nAccept-Language: en-US,en;q=0.9\r\n",
      'timeout' => 25,
    ],
  ]);
  return @file_get_contents($url, false, $context) ?: '';
}

function transfermarkt_players(string $html): array {
  $players = [];
  if ($html === '') return $players;
  libxml_use_internal_errors(true);
  $dom = new DOMDocument();
  @$dom->loadHTML($html);
  $xpath = new DOMXPath($dom);
  $rows = $xpath->query('//table[contains(concat(" ", normalize-space(@class), " "), " items ")]/tbody/tr[td[contains(concat(" ", normalize-space(@class), " "), " posrela ")]]');
  foreach ($rows as $row) {
    $link = $xpath->query('.//td[contains(concat(" ", normalize-space(@class), " "), " hauptlink ")]/a', $row)->item(0);
    $name = $link ? clean_text($link->textContent) : '';
    if ($name === '') continue;
    $countries = [];
    foreach ($xpath->query('.//img[contains(concat(" ", normalize-space(@class), " "), " flaggenrahmen ")]', $row) as $flag) {
      $country = clean_text($flag->getAttribute('title') ?: $flag->getAttribute('alt'));
      if ($country !== '') $countries[] = $country;
    }
    if ($countries) $players[name_key($name)] = ['name' => $name, 'countries' => array_values(array_unique($countries))];
  }
  return $players;
}

$legacy = json_decode((string)file_get_contents($namesFile), true);
if (!is_array($legacy)) {
  fwrite(STDERR, "Could not read {$namesFile}\n");
  exit(1);
}

$out = [];
$total = 0;
$matched = 0;
$missing = [];

foreach ($teamUrls as $team => $url) {
  $remotePlayers = transfermarkt_players(fetch_transfermarkt($url));
  $localPlayers = is_array($legacy[$team] ?? null) ? $legacy[$team] : [];
  foreach ($localPlayers as $player) {
    $name = clean_text((string)($player['name'] ?? ''));
    if ($name === '') continue;
    $total++;
    $remote = $remotePlayers[name_key($name)] ?? null;
    if (!$remote) {
      $missing[$team][] = $name;
      continue;
    }
    $countries = $remote['countries'];
    $codes = array_values(array_filter(array_map(fn($country) => country_code($country, $countryCodeMap), $countries)));
    $out[$team][$name] = [
      'country' => $countries[0],
      'code' => country_code($countries[0], $countryCodeMap),
      'countries' => $countries,
      'countryCodes' => array_values(array_unique($codes)),
    ];
    $matched++;
  }
  usleep(150000);
}

ksort($out);
foreach ($out as &$players) ksort($players);
unset($players);

$json = json_encode($out, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
if (!is_string($json)) {
  fwrite(STDERR, "Could not encode player nationalities\n");
  exit(1);
}
file_put_contents($outFile, $json . PHP_EOL);

echo "Wrote {$outFile}\n";
echo "Matched {$matched} of {$total} local National League players\n";
foreach ($missing as $team => $players) {
  echo $team . ' missing: ' . implode(', ', $players) . PHP_EOL;
}
