<?php

declare(strict_types=1);

/**
 * Release guard: every flag the admin can render must exist in the self-hosted subset.
 *
 * The admin no longer loads flag-icons from a CDN that carries all ~260 countries, so a
 * language added to Translator::flagCode() without re-running bin/build-flag-icons.php
 * renders an empty square — no error, no log, nothing to notice until a customer does.
 *
 * The list of codes is derived from the map itself (bin/_flag_codes.php), never restated
 * here: a guard that carries its own copy of the list goes stale exactly when the thing
 * it guards does.
 *
 * Run from the repo root:  php bin/check-flag-icons.php
 */

$root    = dirname(__DIR__);
$cssFile = $root . '/templates/admin/assets/flag-icons/flag-icons.css';
$flagDir = $root . '/templates/admin/assets/flag-icons/flags/1x1';

if (!is_file($cssFile)) {
    fwrite(STDERR, "FLAG_ICONS_FAIL: missing " . $cssFile . " — run bin/build-flag-icons.php\n");
    exit(1);
}

$sets     = require __DIR__ . '/_flag_codes.php';
$required = $sets['required'];
$css      = (string) file_get_contents($cssFile);

$noRule = [];
$noSvg  = [];
foreach ($required as $code) {
    if (!str_contains($css, '.fi-' . $code . '{')) {
        $noRule[] = $code;
    }
    if (!is_file($flagDir . '/' . $code . '.svg')) {
        $noSvg[] = $code;
    }
}

 
foreach (['.fi{', '.fis{'] as $base) {
    if (!str_contains($css, $base)) {
        fwrite(STDERR, "FLAG_ICONS_FAIL: base rule " . rtrim($base, '{') . " missing from the subset CSS\n");
        exit(1);
    }
}

if ($noRule || $noSvg) {
    fwrite(STDERR, "FLAG_ICONS_FAIL: the self-hosted flag subset is out of date — run bin/build-flag-icons.php\n");
    if ($noRule) {
        fwrite(STDERR, "  no CSS rule for: " . implode(', ', $noRule) . "\n");
    }
    if ($noSvg) {
        fwrite(STDERR, "  no SVG file for: " . implode(', ', $noSvg) . "\n");
    }
    exit(1);
}

fwrite(STDOUT, "FLAG_ICONS_OK (" . count($required) . " required codes, " . count(glob($flagDir . '/*.svg') ?: []) . " svg shipped)\n");
exit(0);
