#!/usr/bin/env python3
"""site-postwrite-derivation-gate — PostToolUse check: site source edits name their stale derivatives.

site/sitemap.json feeds GENERATED surfaces (site/llms.txt, the patterns/
templates index) that go stale the moment a route or content path changes
without a regen. This hook feeds that regeneration obligation back at
write-time.

(Before ADR-0072 Decision 2 / gh#2410, this hook also flagged
site/pages/**/*.html fragment edits whose route the site-a2ui ledger
marked "converted" — the docs site rendered such routes from a GENERATED
site-a2ui/pages/<slug>.a2ui.json artifact, so a fragment-only edit changed
nothing users saw. That render path retired; every route now renders
straight from its fragment, so a fragment edit is never stale on its own
and needs no nudge.)

Usage:
  site-postwrite-derivation-gate --hook       # PostToolUse mode: event JSON on stdin
  site-postwrite-derivation-gate selftest     # prove matcher on fixtures
"""
import json
import sys

SITEMAP_MARKER = "site/sitemap.json"


def classify(path):
    """→ "sitemap" if `path` is site/sitemap.json, else None."""
    if path and path.endswith(SITEMAP_MARKER):
        return "sitemap"
    return None


SITEMAP_REASON = (
    "site-postwrite-derivation-gate · site/sitemap.json feeds GENERATED surfaces that are "
    "now stale: site/llms.txt (`npm run build:llms`) and the patterns/templates index "
    "(`npm run build:patterns-index`)."
)


def hook_mode():
    try:
        event = json.load(sys.stdin)
    except Exception:
        return 0
    tool_input = event.get("tool_input") or {}
    if classify(tool_input.get("file_path") or "") == "sitemap":
        print(json.dumps({"decision": "block", "reason": SITEMAP_REASON}))
    return 0


def selftest():
    scope_cases = [
        ("/repo/site/sitemap.json", "sitemap"),
        ("/repo/site/pages/architecture/ontology.html", None),
        ("site/pages/guides/testing.html", None),
        ("/repo/site/pages/patterns/index.html", None),
        ("/repo/site/site.js", None),
        ("/repo/site/pages/architecture/notes.txt", None),
        ("/repo/apps/tasks/app/index.html", None),
    ]
    for path, expected in scope_cases:
        if classify(path) != expected:
            print(f"selftest: FAIL scope {path} → {classify(path)} expected {expected}")
            return 1
    print("selftest: PASS")
    return 0


if __name__ == "__main__":
    if "selftest" in sys.argv:
        sys.exit(selftest())
    if "--hook" in sys.argv:
        sys.exit(hook_mode())
    print(__doc__)
    sys.exit(0)
