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

ROOT = Path(__file__).resolve().parents[2]
RULES = ROOT / "knowledge" / "rules" / "critical-facts.yml"


def parse_rules(path: Path):
    lines = path.read_text(encoding="utf-8").splitlines()
    checks = []
    cur = None
    in_must = False
    for raw in lines:
        line = raw.rstrip("\n")
        s = line.strip()
        if not s or s.startswith("#"):
            continue
        if s.startswith("- id:"):
            if cur:
                checks.append(cur)
            cur = {"id": s.split(":", 1)[1].strip(), "mustContain": []}
            in_must = False
            continue
        if cur is None:
            continue
        if s.startswith("description:"):
            cur["description"] = s.split(":", 1)[1].strip()
        elif s.startswith("file:"):
            cur["file"] = s.split(":", 1)[1].strip()
        elif s.startswith("mustContain:"):
            in_must = True
        elif in_must and s.startswith("-"):
            val = s[1:].strip().strip('"').strip("'")
            cur["mustContain"].append(val)
        elif not s.startswith("-"):
            in_must = False
    if cur:
        checks.append(cur)
    return checks


def run():
    if not RULES.exists():
        print("ERROR: rules file missing", file=sys.stderr)
        return 2
    checks = parse_rules(RULES)
    failed = 0
    total = 0
    print("# Critical Facts Check")
    for c in checks:
        total += 1
        fp = ROOT / c.get("file", "")
        ok = True
        missing = []
        if not fp.exists():
            ok = False
            missing = [f"file not found: {fp}"]
        else:
            txt = fp.read_text(encoding="utf-8", errors="ignore")
            for needle in c.get("mustContain", []):
                if needle not in txt:
                    ok = False
                    missing.append(needle)
        status = "PASS" if ok else "FAIL"
        print(f"- [{status}] {c.get('id','unknown')}: {c.get('description','')}")
        if not ok:
            failed += 1
            for m in missing:
                print(f"  - missing: {m}")
    print(f"\nSummary: {total-failed}/{total} passed")
    return 1 if failed else 0


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