#!/usr/bin/env python3
"""
Check that the Tailwind classes used in Blade actually reached public/css/app.css.

Written because grepping the compiled file by hand kept giving false alarms:
Tailwind escapes : . [ ] / % and , in selectors, so a plain grep for
"group-hover:visible" finds nothing even though ".group-hover\\:visible" is
right there. Three separate "the CSS is broken" panics came from that.

    python3 scripts/check-css.py                 # scan every .blade.php
    python3 scripts/check-css.py btn--gold ...   # check specific classes
"""

import pathlib
import re
import sys

ROOT = pathlib.Path(__file__).resolve().parent.parent
CSS = ROOT / "public/css/app.css"
VIEWS = ROOT / "resources/views"

# Classes Tailwind never emits because they aren't utilities, or that come from
# the component layer under a different name.
IGNORE_PREFIX = ("btn", "card", "tile", "field", "display", "readout",
                 "rule-label", "plume", "note-bar", "grain", "prose-air",
                 "scent-strip", "group", "peer", "sr-only")


# Every character Tailwind backslash-escapes in a generated selector.
ESCAPED = ":.[]/%,()#!*+~<>='\""


def escape(cls: str) -> str:
    """Match Tailwind's selector escaping."""
    return "".join("\\" + c if c in ESCAPED else c for c in cls)


def present(css: str, cls: str) -> bool:
    return ("." + escape(cls)) in css


def classes_in_views() -> set[str]:
    found: set[str] = set()
    for f in VIEWS.rglob("*.blade.php"):
        # The PDF template ships its own <style> block — dompdf never sees
        # Tailwind, so its class names are not expected in app.css.
        if "/pdf/" in str(f):
            continue
        text = f.read_text()
        for attr in re.findall(r'class="([^"]*)"', text):
            # Skip Blade expressions — {{ }} produces classes we can't see here.
            if "{{" in attr or "{!!" in attr:
                continue
            found.update(attr.split())
    return found


def main() -> int:
    if not CSS.exists():
        print(f"  {CSS} not found — run: npx @tailwindcss/cli -i resources/css/app.css -o public/css/app.css --minify")
        return 1

    css = CSS.read_text()

    if len(sys.argv) > 1:
        targets = sys.argv[1:]
    else:
        targets = sorted(
            c for c in classes_in_views()
            if not c.startswith(IGNORE_PREFIX) and not c.startswith("!")
        )

    missing = [c for c in targets if not present(css, c)]

    for c in missing:
        print(f"  MISSING  {c}")

    print(f"\n  {len(targets) - len(missing)}/{len(targets)} classes present in the compiled CSS")

    if missing:
        print("  Rebuild:  npx @tailwindcss/cli -i resources/css/app.css -o public/css/app.css --minify")
        return 1

    return 0


if __name__ == "__main__":
    raise SystemExit(main())
