<?php
declare(strict_types=1);

require_once __DIR__ . '/../.lib/api/bootstrap.php';
require_once __DIR__ . '/../.lib/api/core.php';
require_once __DIR__ . '/../.lib/api/squad_training_match.php';
require_once __DIR__ . '/../.lib/api/manager_finance_market.php';
require_once __DIR__ . '/../.lib/manager_progression.php';
require_once __DIR__ . '/../.lib/api/manager_catalog.php';

$force = in_array('--force', $argv, true);
$only = [];
foreach (array_slice($argv, 1) as $arg) {
  if (str_starts_with($arg, '--')) continue;
  $slug = str_replace('-', '_', source_team_id($arg));
  if ($slug !== '') $only[$slug] = true;
}

if (!is_dir(TEAM_PLAYER_DIR)) mkdir(TEAM_PLAYER_DIR, 0777, true);

function tm_fetch(string $url): string {
  $context = stream_context_create([
    'http' => [
      'method' => 'GET',
      'timeout' => 20,
      'ignore_errors' => true,
      'header' => implode("\r\n", [
        'User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 Chrome/124 Safari/537.36',
        'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
        'Accept-Language: en-GB,en;q=0.9',
      ]),
    ],
  ]);
  $body = @file_get_contents($url, false, $context);
  return is_string($body) ? $body : '';
}

function tm_plain(string $value): string {
  $value = html_entity_decode($value, ENT_QUOTES | ENT_HTML5, 'UTF-8');
  $value = preg_replace('/\s+/u', ' ', $value) ?? $value;
  return trim($value);
}

function tm_norm(string $value): string {
  $value = strtolower(tm_plain($value));
  $value = str_replace('&', 'and', $value);
  $value = preg_replace('/\b(fc|afc|cf|town|city|united|rovers|wanderers|albion|athletic|county|hotspur|dons)\b/u', '', $value) ?? $value;
  return preg_replace('/[^a-z0-9]+/u', '', $value) ?? '';
}

function tm_shirt_name(string $name): string {
  $plain = tm_plain($name);
  $parts = preg_split('/\s+/u', str_replace('-', ' ', $plain)) ?: [];
  $last = trim((string)end($parts));
  return strtoupper($last !== '' ? $last : $plain);
}

function tm_country_code(string $country): string {
  $code = player_country_code($country);
  if ($code !== '') return $code;
  $map = [
    'bosnia-herzegovina' => 'ba',
    'cape verde' => 'cv',
    'curacao' => 'cw',
    'czech republic' => 'cz',
    'guinea-bissau' => 'gw',
    'north macedonia' => 'mk',
    'republic of ireland' => 'ie',
    'serbia' => 'rs',
    'slovakia' => 'sk',
    'trinidad and tobago' => 'tt',
  ];
  return $map[strtolower(trim($country))] ?? '';
}

function tm_club_candidates(string $query): array {
  $html = tm_fetch('https://www.transfermarkt.com/schnellsuche/ergebnis/schnellsuche?query=' . rawurlencode($query));
  if ($html === '') return [];
  preg_match_all('~<tr[^>]*>.*?</tr>~is', $html, $rows);
  $out = [];
  foreach ($rows[0] as $row) {
    if (!preg_match('~href="/([^"]+)/startseite/verein/(\d+)"[^>]*>(.*?)</a>~is', $row, $match)) continue;
    $title = tm_plain(strip_tags($match[3]));
    if ($title === '' || preg_match('/\b(U\d+|U21|U23|B|Women|Youth|Academy)\b/i', $title)) continue;
    $league = '';
    if (preg_match('~<a title="([^"]+)" href="/[^"]+/startseite/wettbewerb/[^"]+"~i', $row, $leagueMatch)) {
      $league = tm_plain($leagueMatch[1]);
    }
    $out[] = [
      'title' => $title,
      'slug' => '/' . trim($match[1], '/'),
      'id' => (int)$match[2],
      'league' => $league,
      'row' => $row,
    ];
  }
  return $out;
}

function tm_pick_club(string $teamName): ?array {
  $known = [
    'brightonandhove' => ['title' => 'Brighton & Hove Albion', 'slug' => '/brighton-amp-hove-albion', 'id' => 1237, 'league' => 'Premier League', 'row' => ''],
  ];
  $key = tm_norm($teamName);
  if (isset($known[$key])) return $known[$key];
  $candidates = tm_club_candidates($teamName);
  if (!$candidates) return null;
  $target = tm_norm($teamName);
  usort($candidates, function (array $a, array $b) use ($target): int {
    $an = tm_norm($a['title']);
    $bn = tm_norm($b['title']);
    $as = ($an === $target ? 100 : (str_contains($an, $target) || str_contains($target, $an) ? 50 : 0));
    $bs = ($bn === $target ? 100 : (str_contains($bn, $target) || str_contains($target, $bn) ? 50 : 0));
    return $bs <=> $as;
  });
  return $candidates[0];
}

function tm_dom(string $html): ?DOMXPath {
  if ($html === '') return null;
  libxml_use_internal_errors(true);
  $dom = new DOMDocument();
  if (!$dom->loadHTML($html)) return null;
  return new DOMXPath($dom);
}

function tm_node_text(?DOMNode $node): string {
  return $node ? tm_plain($node->textContent) : '';
}

function tm_first(DOMXPath $xp, string $query, DOMNode $ctx): ?DOMNode {
  $nodes = $xp->query($query, $ctx);
  return $nodes && $nodes->length ? $nodes->item(0) : null;
}

function tm_squad_players(string $clubSlug, int $clubId, int $seasonId = 2026): array {
  $url = 'https://www.transfermarkt.com' . $clubSlug . '/kader/verein/' . $clubId . '/saison_id/' . $seasonId;
  $xp = tm_dom(tm_fetch($url));
  if (!$xp) return ['url' => $url, 'players' => []];
  $rows = $xp->query('//table[contains(concat(" ", normalize-space(@class), " "), " items ")]//tr[contains(@class, "odd") or contains(@class, "even")]');
  $players = [];
  foreach ($rows ?: [] as $row) {
    if (!$row instanceof DOMNode) continue;
    $link = tm_first($xp, './/td[contains(@class, "posrela")]//a[contains(@href, "/profil/spieler/")]', $row);
    $name = tm_node_text($link);
    if ($name === '' || isset($players[$name])) continue;
    $numberText = tm_node_text(tm_first($xp, './/td[contains(@class, "rueckennummer")]//div', $row));
    $roleText = tm_node_text(tm_first($xp, './/td[contains(@class, "posrela")]//td[contains(@class, "hauptlink")]', $row));
    $roleText = tm_plain(str_replace($name, '', $roleText));
    $roleText = preg_replace('/^\s*[-0-9]+\s*/', '', $roleText) ?? $roleText;
    if ($roleText === '') $roleText = tm_plain((string)(tm_first($xp, './/td[contains(@class, "rueckennummer")]', $row)?->attributes?->getNamedItem('title')?->nodeValue ?? ''));
    $countries = [];
    $countryCodes = [];
    $flags = $xp->query('.//img[contains(@class, "flaggenrahmen")]', $row);
    foreach ($flags ?: [] as $flag) {
      if (!$flag instanceof DOMElement) continue;
      $country = tm_plain($flag->getAttribute('title') ?: $flag->getAttribute('alt'));
      if ($country === '' || in_array($country, $countries, true)) continue;
      $countries[] = $country;
      $code = tm_country_code($country);
      if ($code !== '' && !in_array($code, $countryCodes, true)) $countryCodes[] = $code;
    }
    $player = [
      'name' => $name,
      'shirtName' => tm_shirt_name($name),
      'legacyRole' => $roleText,
    ];
    if ($numberText !== '' && $numberText !== '-') $player['legacyNumber'] = (int)$numberText;
    if ($countries) {
      $player['country'] = $countries[0];
      $player['countries'] = $countries;
    }
    if ($countryCodes) {
      $player['countryCode'] = $countryCodes[0];
      $player['countryCodes'] = $countryCodes;
    }
    if ($link instanceof DOMElement) $player['source'] = 'https://www.transfermarkt.com' . $link->getAttribute('href');
    $players[$name] = $player;
  }
  return ['url' => $url, 'players' => array_values($players)];
}

$teams = [];
for ($level = 1; $level <= 5; $level++) {
  foreach (manager_division_teams($level) as $team) {
    $team['managerDivisionLevel'] = $level;
    $team['managerDivisionName'] = manager_division_name($level);
    $teams[] = $team;
  }
}

$ok = 0;
$skip = 0;
$fail = 0;
foreach ($teams as $team) {
  $sourceId = source_team_id((string)($team['sourceId'] ?? $team['id'] ?? ''));
  $slug = str_replace('-', '_', $sourceId);
  if ($only && empty($only[$slug])) continue;
  $file = TEAM_PLAYER_DIR . '/' . $slug . '.json';
  if (!$force && is_file($file)) {
    echo "SKIP {$slug} existing file\n";
    $skip++;
    continue;
  }
  $club = tm_pick_club((string)$team['name']);
  if (!$club) {
    echo "FAIL {$slug} no club match\n";
    $fail++;
    continue;
  }
  $squad = tm_squad_players((string)$club['slug'], (int)$club['id']);
  if (count($squad['players']) < 11) {
    echo "FAIL {$slug} {$club['title']} only " . count($squad['players']) . " players\n";
    $fail++;
    continue;
  }
  $payload = [
    'updated' => gmdate('Y-m-d'),
    'sourceType' => 'transfermarkt_26_27_batch',
    'primarySource' => $squad['url'],
    'transfermarktTeamId' => $club['id'],
    'transfermarktClubName' => $club['title'],
    'divisionName' => $team['managerDivisionName'],
    'players' => $squad['players'],
  ];
  file_put_contents($file, json_encode($payload, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE) . "\n");
  echo "OK {$slug} {$club['title']} " . count($squad['players']) . " players\n";
  $ok++;
  usleep(250000);
}

echo "summary ok={$ok} skipped={$skip} failed={$fail}\n";
