"""Sprite integrity — the vendored icon vocabulary stays canon (M1 P4.1).

The sprite is a VERBATIM copy of the GENERATED
``mgf-brand/brand/assets/icons/icons-sprite.svg`` @ ``865477b`` (the F3
founder-approved set, Brand Book Part VIb). These tests pin the icon LAW —
naming, grid, theming — and the exact bytes, so any re-vendor is a deliberate,
reviewed act (the same discipline as the generated token layer).
"""

from __future__ import annotations

import hashlib
import re

import pytest

from mgf.brand_web import static_dir

# sha256 of the canon sprite @ mgf-brand 865477b — update ONLY when
# deliberately re-vendoring a newer canon sprite.
CANON_SHA256 = "392322edc7a3ec2ed6ca9dbac8b6a6cc55d359a162ef752920949c04f6dfd774"
CANON_COUNT = 42
KEBAB_ID = re.compile(r"^mgf-icon-[a-z0-9]+(?:-[a-z0-9]+)*$")


def _sprite_text() -> str:
    return (static_dir() / "icons" / "icons-sprite.svg").read_text(encoding="utf-8")


def _symbols() -> list[tuple[str, str]]:
    """(id, full symbol tag) for every <symbol> in the sprite.

    XML comments are stripped first — the generated provenance header mentions
    ``<symbol>`` in prose.
    """
    txt = re.sub(r"<!--.*?-->", "", _sprite_text(), flags=re.DOTALL)
    tags = re.findall(r"<symbol\b[^>]*>", txt)
    out = []
    for tag in tags:
        m = re.search(r'id="([^"]+)"', tag)
        assert m, f"symbol without id: {tag}"
        out.append((m.group(1), tag))
    return out


@pytest.mark.smoke
def test_sprite_ships() -> None:
    assert (static_dir() / "icons" / "icons-sprite.svg").is_file()


def test_sprite_is_byte_identical_to_canon() -> None:
    """Provenance pin: the file is the canon sprite, byte for byte."""
    digest = hashlib.sha256((static_dir() / "icons" / "icons-sprite.svg").read_bytes()).hexdigest()
    assert digest == CANON_SHA256


def test_every_symbol_id_is_mgf_icon_kebab() -> None:
    ids = [sid for sid, _ in _symbols()]
    bad = [sid for sid in ids if not KEBAB_ID.match(sid)]
    assert not bad, f"non-canon symbol ids: {bad}"


def test_symbol_ids_are_unique_and_the_full_42() -> None:
    ids = [sid for sid, _ in _symbols()]
    assert len(ids) == len(set(ids)), "duplicate symbol ids"
    assert len(ids) == CANON_COUNT, f"expected the {CANON_COUNT}-icon set, got {len(ids)}"


def test_every_symbol_is_on_the_24_grid() -> None:
    off_grid = [sid for sid, tag in _symbols() if 'viewBox="0 0 24 24"' not in tag]
    assert not off_grid, f"symbols off the 24x24 grid: {off_grid}"


def test_every_symbol_themes_via_currentcolor() -> None:
    """One drawing serves every ground — icons are monochrome by law."""
    unthemed = [sid for sid, tag in _symbols() if 'stroke="currentColor"' not in tag]
    assert not unthemed, f"symbols not stroked with currentColor: {unthemed}"
