#!/usr/bin/env python3
import hashlib
import re
import sys
from pathlib import Path

def stop(code: str, detail: str) -> None:
    print("RESULT=STOP_ROUTER_REFERENCE_SHA")
    print(f"STOP_CODE={code}")
    print(f"STOP_DETAIL={detail}")
    raise SystemExit(2)

if len(sys.argv) not in (3, 4) or sys.argv[1] not in ("validate", "verify"):
    stop("USAGE", "router-reference-sha validate FILE | verify FILE ROOT")

mode = sys.argv[1]
reference = Path(sys.argv[2])
if not reference.is_file():
    stop("REFERENCE_MISSING", str(reference))

rows: list[tuple[str, str]] = []
for line_number, raw in enumerate(reference.read_text(encoding="utf-8").splitlines(), 1):
    if not raw or raw.lstrip().startswith("#"):
        continue
    match = re.fullmatch(r"([0-9a-f]{64})  ([^\x00\r\n]+)", raw)
    if not match:
        stop("REFERENCE_FORMAT", f"{reference}:{line_number}")
    relative = match.group(2)
    relative_path = Path(relative)
    if relative_path.is_absolute() or ".." in relative_path.parts or relative.startswith("./") or "\\" in relative:
        stop("REFERENCE_PATH", f"{reference}:{line_number}:{relative}")
    rows.append((match.group(1), relative))

if not rows:
    stop("REFERENCE_EMPTY", str(reference))

if mode == "verify":
    if len(sys.argv) != 4:
        stop("USAGE", "verify requires ROOT")
    root = Path(sys.argv[3]).resolve()
    for expected, relative in rows:
        target = (root / relative).resolve()
        if target != root and root not in target.parents:
            stop("REFERENCE_ESCAPE", relative)
        if not target.is_file():
            stop("TARGET_MISSING", relative)
        actual = hashlib.sha256(target.read_bytes()).hexdigest()
        if actual != expected:
            stop("SHA_MISMATCH", f"{relative}:{actual}")

print("RESULT=PASS_ROUTER_REFERENCE_SHA")
print(f"REFERENCE_ROW_COUNT={len(rows)}")
print(f"REFERENCE_MODE={mode}")
