"""Self-heal the committed example Look/Identity placeholder refs.

The example SSOT files (``recoil/config/looks/noir_neon.yaml`` +
``recoil/config/identities/kara_voss.yaml``) reference tiny placeholder ref
images. ``look_loader.load_registries()`` is fail-fast — it raises if any
referenced ref file is missing on disk. Those placeholder PNGs are
deliberately NOT committed: ``.gitignore`` carries a "C6 evicted-media guard"
that blocks all binaries (``*.png`` etc.) from re-entering the repo.

Consequence without this fixture: on a fresh checkout (CI, a peer machine
after cross-machine sync) the binaries are absent, so
``test_committed_registries_parse`` — and any standalone ``load_registries()``
call — fails through no fault of the code. This session-scoped autouse fixture
regenerates the missing placeholders from the YAML's own ref lists before any
test runs, keeping the example SSOT resolvable everywhere WITHOUT committing
binaries. Real production looks ship their real refs on disk the same way
(refs live outside git by repo policy).
"""

from __future__ import annotations

import struct
import zlib
from pathlib import Path

import pytest
import yaml

from recoil.pipeline._lib.look_loader import (
    IDENTITIES_DIR,
    LOOKS_DIR,
    REF_ROOT,
)


def _write_placeholder_png(path: Path) -> None:
    """Write a minimal valid 1x1 RGBA PNG (stdlib only) — identical bytes to
    the test helper's ``_write_png``."""
    path.parent.mkdir(parents=True, exist_ok=True)
    raw = b"\x00" + b"\x00\x00\x00\xff"

    def chunk(typ: bytes, data: bytes) -> bytes:
        c = typ + data
        return struct.pack(">I", len(data)) + c + struct.pack(">I", zlib.crc32(c) & 0xFFFFFFFF)

    sig = b"\x89PNG\r\n\x1a\n"
    ihdr = struct.pack(">IIBBBBB", 1, 1, 8, 6, 0, 0, 0)
    idat = zlib.compress(raw)
    path.write_bytes(sig + chunk(b"IHDR", ihdr) + chunk(b"IDAT", idat) + chunk(b"IEND", b""))


def _ref_paths_from(yaml_dir: Path, ref_key: str) -> list[str]:
    """Collect every ``path`` under ``ref_key`` across all YAMLs in a dir."""
    paths: list[str] = []
    if not yaml_dir.is_dir():
        return paths
    for yml in sorted(yaml_dir.glob("*.yaml")):
        try:
            data = yaml.safe_load(yml.read_text()) or {}
        except yaml.YAMLError:
            continue
        for ref in data.get(ref_key, []) or []:
            if isinstance(ref, dict) and ref.get("path"):
                paths.append(ref["path"])
    return paths


@pytest.fixture(scope="session", autouse=True)
def _ensure_committed_example_refs() -> None:
    """Regenerate any missing committed-example placeholder ref (before tests)."""
    rel_paths = _ref_paths_from(LOOKS_DIR, "style_refs") + _ref_paths_from(
        IDENTITIES_DIR, "ref_set"
    )
    for rel in rel_paths:
        target = REF_ROOT / rel
        if not target.exists():
            _write_placeholder_png(target)
