<?php

declare(strict_types=1);

/**
 * Release guard: public/assets/admin/tailwind.css must match a FRESH build of the
 * current tree.
 *
 * A build artifact that drifts from its source is the worst kind of defect: a template
 * gains a Tailwind class, nobody rebuilds, the class is absent from the stylesheet, and
 * the element renders unstyled with no error in any log. This turns that silent drift
 * into a failed release.
 *
 * Run from the repo root:  php bin/check-admin-css.php
 * Exit 0 = in sync. Exit 1 = stale (or the toolchain is missing).
 */

$root  = dirname(__DIR__);
$out   = $root . '/templates/admin/assets/tailwind.css';
$build = $root . '/build/admin-css';

if (!is_file($out)) {
    fwrite(STDERR, "ADMIN_CSS_FAIL: missing " . $out . "\n");
    exit(1);
}
if (!is_dir($build . '/node_modules')) {
     
     
    fwrite(STDOUT, "ADMIN_CSS_SKIP: build toolchain absent (build/admin-css/node_modules) — cannot verify freshness\n");
    exit(0);
}

$tmp = tempnam(sys_get_temp_dir(), 'admincss');
if ($tmp === false) {
    fwrite(STDERR, "ADMIN_CSS_FAIL: cannot create a temp file\n");
    exit(1);
}
$tmpCss = $tmp . '.css';
@unlink($tmp);

$cmd = sprintf(
    'cd %s && ./node_modules/.bin/tailwindcss -c tailwind.config.js -i input.css -o %s --minify 2>&1',
    escapeshellarg($build),
    escapeshellarg($tmpCss)
);
exec($cmd, $lines, $rc);
if ($rc !== 0 || !is_file($tmpCss)) {
    @unlink($tmpCss);
    fwrite(STDERR, "ADMIN_CSS_FAIL: tailwind build failed:\n" . implode("\n", $lines) . "\n");
    exit(1);
}

$fresh     = (string) file_get_contents($tmpCss);
$committed = (string) file_get_contents($out);
@unlink($tmpCss);

if (hash('sha256', $fresh) === hash('sha256', $committed)) {
    fwrite(STDOUT, "ADMIN_CSS_OK (" . strlen($committed) . " bytes)\n");
    exit(0);
}

 
 
$classes = static function (string $css): array {
    preg_match_all('/(?<![\w\\\\-])\.((?:[\w-]|\\\\.)+)/', $css, $m);
    return array_unique($m[1] ?? []);
};
$missing = array_slice(array_diff($classes($fresh), $classes($committed)), 0, 25);

fwrite(STDERR, "ADMIN_CSS_FAIL: public/assets/admin/tailwind.css is STALE — rebuild with bin/build-admin-css.sh\n");
fwrite(STDERR, "  committed: " . strlen($committed) . " bytes, fresh build: " . strlen($fresh) . " bytes\n");
if ($missing) {
    fwrite(STDERR, "  classes present in a fresh build but MISSING from the committed file:\n");
    foreach ($missing as $c) {
        fwrite(STDERR, "    ." . $c . "\n");
    }
}
exit(1);
