<?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';

$only = array_map(fn($value) => str_replace('-', '_', source_team_id((string)$value)), array_slice($argv, 1));
$only = array_values(array_filter($only, fn($value) => $value !== ''));
$filter = $only ? array_fill_keys($only, true) : null;

$summary = ['teams' => 0, 'missing' => 0, 'mismatch' => 0, 'thin' => 0];
for ($level = 1; $level <= 5; $level++) {
  foreach (manager_division_teams($level) as $team) {
    $sourceId = source_team_id((string)($team['sourceId'] ?? $team['id'] ?? ''));
    $slug = str_replace('-', '_', $sourceId);
    if ($filter !== null && empty($filter[$slug])) continue;
    $file = TEAM_PLAYER_DIR . '/' . $slug . '.json';
    $players = legacy_team_players($sourceId, (string)$team['name']);
    $squad = make_named_squad('home', (int)($team['baseRating'] ?? 43), $sourceId, (string)$team['name']);
    $squadCount = count($squad['starters'] ?? []) + count($squad['bench'] ?? []);
    $source = is_file($file) ? 'team-file' : 'shared-catalog';
    $flags = [];
    if (!is_file($file)) {
      $flags[] = 'missing-file';
      $summary['missing']++;
    }
    if ($squadCount !== count($players)) {
      $flags[] = 'count-mismatch';
      $summary['mismatch']++;
    }
    if (count($players) < 18) {
      $flags[] = 'thin';
      $summary['thin']++;
    }
    $summary['teams']++;
    printf(
      "%-28s %2d players  %2d squad  %-13s %s\n",
      $slug,
      count($players),
      $squadCount,
      $source,
      implode(',', $flags)
    );
  }
}
printf(
  "summary teams=%d missing=%d mismatch=%d thin=%d\n",
  $summary['teams'],
  $summary['missing'],
  $summary['mismatch'],
  $summary['thin']
);
