<?php

declare(strict_types=1);

/**
 * The flag codes the admin can render, DERIVED from Translator::flagCode().
 *
 * Deliberately not a second hand-written list: a copy of the map would drift the first
 * time somebody adds a language, and the only symptom would be a missing flag — nothing
 * logged, nothing failing. Shared by bin/build-flag-icons.php (which copies the SVGs) and
 * bin/check-flag-icons.php (which fails the release when a required one is absent).
 *
 * Returns ['required' => string[], 'optional' => string[]]:
 *   required — the map's VALUES: what flagCode() returns for a shipped language. A missing
 *              one is a visible defect, so the release must fail.
 *   optional — the map's KEYS: flagCode() falls back to the language code itself for a
 *              language the map does not cover. Some of those happen to be real country
 *              codes ('fr', 'it', 'de'…) and are worth shipping; the rest ('en', 'zh'…)
 *              are not countries and have no upstream SVG. Best-effort only.
 */

if (!class_exists('Translator', false)) {
    require_once dirname(__DIR__) . '/src/Core/Translator.php';
}

$m = new ReflectionMethod('Translator', 'flagCode');
$file = (string) $m->getFileName();
$lines = file($file, FILE_IGNORE_NEW_LINES) ?: [];
$body = implode("\n", array_slice($lines, $m->getStartLine() - 1, $m->getEndLine() - $m->getStartLine() + 1));

if (!preg_match_all("/'([a-z]{2})'\s*=>\s*'([a-z]{2})'/", $body, $pairs, PREG_SET_ORDER)) {
    fwrite(STDERR, "FLAG_CODES_FAIL: could not read the map out of Translator::flagCode()\n");
    exit(1);
}
if (count($pairs) < 20) {
    fwrite(STDERR, "FLAG_CODES_FAIL: only " . count($pairs) . " pairs parsed — the map shape changed\n");
    exit(1);
}

$required = [];
$optional = [];
foreach ($pairs as $p) {
    $required[$p[2]] = true;
    $optional[$p[1]] = true;
}
$optional = array_diff_key($optional, $required);

$required = array_keys($required);
$optional = array_keys($optional);
sort($required);
sort($optional);

return ['required' => $required, 'optional' => $optional];
