from __future__ import annotations

import sys
from pathlib import Path

import yaml


def main() -> int:
    if len(sys.argv) < 3 or sys.argv[1] != "--index":
        print("usage: validate_adr_index.py --index governance/adr_index.yaml")
        return 2
    index_path = Path(sys.argv[2])
    data = yaml.safe_load(index_path.read_text(encoding="utf-8"))
    entries = data.get("entries", [])
    errors: list[str] = []
    if data.get("adr_count") != len(entries):
        errors.append("adr_count mismatch")
    allowed = {"proposed", "accepted", "superseded", "deprecated"}
    for entry in entries:
        if entry.get("status") not in allowed:
            errors.append(f"invalid status: {entry.get('adr_id')}")
        path = Path(entry.get("path", ""))
        if not path.exists():
            errors.append(f"missing adr file: {path}")
        else:
            text = path.read_text(encoding="utf-8")
            for required in ("## Context", "## Decision", "## Consequences", "## Rollback"):
                if required not in text:
                    errors.append(f"missing section {required} in {path}")
    if errors:
        print("FAIL")
        for err in errors:
            print(err)
        return 1
    print("ADR_INDEX_OK")
    return 0


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

