"""build_agents_rule_hashes_v1.py — AGENTS rule hash migration"""
from __future__ import annotations

import hashlib
import json
from pathlib import Path

import yaml


ROOT = Path(__file__).resolve().parents[1]
INDEX = ROOT / "governance" / "agents_index.yaml"
OUTPUT = ROOT / "governance" / "agents_rule_hashes.yaml"


def sha256(path: Path) -> str:
    return hashlib.sha256(path.read_bytes()).hexdigest()


def main() -> int:
    index = yaml.safe_load(INDEX.read_text(encoding="utf-8")) or {}
    rule_files = index.get("rule_files") if isinstance(index.get("rule_files"), list) else []
    rows = []
    for rel in rule_files:
        path = ROOT / str(rel)
        if path.exists():
            rows.append({"path": str(rel), "sha256": sha256(path)})
    rows.append({"path": "AGENTS.md", "sha256": sha256(ROOT / "AGENTS.md")})
    payload = {
        "schema_version": "agents_rule_hashes.v1",
        "hash_algorithm": "sha256",
        "generated_from": "governance/agents_index.yaml",
        "files": rows,
    }
    OUTPUT.write_text(yaml.safe_dump(payload, sort_keys=False, allow_unicode=True), encoding="utf-8")
    print(json.dumps({"status": "OK", "file_count": len(rows), "output": str(OUTPUT.relative_to(ROOT))}, ensure_ascii=False))
    return 0


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