#!/usr/bin/env python3
"""Report the machine-readable EwoooC security/governance review."""

from __future__ import annotations

import argparse
import json
import sys
from pathlib import Path


ROOT = Path(__file__).resolve().parents[2]
if str(ROOT) not in sys.path:
    sys.path.insert(0, str(ROOT))

from services.security_governance_review_service import (  # noqa: E402
    build_security_governance_review,
)


def _parser() -> argparse.ArgumentParser:
    parser = argparse.ArgumentParser()
    parser.add_argument("--root", type=Path, default=ROOT)
    parser.add_argument("--detail-limit", type=int, default=30)
    parser.add_argument("--compact", action="store_true")
    parser.add_argument(
        "--source-commit",
        default="",
        help="Bind emitted source receipt to the caller-provided Gitea commit SHA.",
    )
    parser.add_argument(
        "--strict",
        action="store_true",
        help="Exit non-zero only for release-blocking source governance failures.",
    )
    return parser


def main(argv: list[str] | None = None) -> int:
    args = _parser().parse_args(argv)
    report = build_security_governance_review(
        root=args.root,
        detail_limit=args.detail_limit,
    )
    source_commit = str(args.source_commit or "").strip()
    if source_commit:
        if len(source_commit) != 40 or any(
            char not in "0123456789abcdefABCDEF" for char in source_commit
        ):
            print("--source-commit must be a 40-character hexadecimal Gitea SHA", file=sys.stderr)
            return 2
        report["receipt_kind"] = "security_governance_source_receipt"
        report["source_commit"] = source_commit
    if args.compact:
        output = {
            "policy": report["policy"],
            "status": report["status"],
            "completion": report["completion"],
            "release_gate": report["release_gate"],
            "next_machine_action": report["next_machine_action"],
        }
    else:
        output = report
    print(json.dumps(output, ensure_ascii=False, indent=2, sort_keys=True))
    if args.strict and report["release_gate"]["status"] != "pass":
        return 1
    return 0


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