#!/usr/bin/env python3
"""Emit the SEC-P0-002 database identity runtime readback without secrets."""

from __future__ import annotations

import argparse
from contextlib import redirect_stdout
from datetime import datetime, timezone
import json
from pathlib import Path
import sys


ROOT = Path(__file__).resolve().parents[2]


def parse_args() -> argparse.Namespace:
    parser = argparse.ArgumentParser()
    parser.add_argument("--compact", action="store_true")
    parser.add_argument("--strict", action="store_true", help="Require canary readiness")
    parser.add_argument(
        "--require-closed",
        action="store_true",
        help="Require database-only authority and complete runtime closure",
    )
    return parser.parse_args()


def main() -> int:
    args = parse_args()
    sys.path.insert(0, str(ROOT))

    with redirect_stdout(sys.stderr):
        from database.manager import get_session
        from services.auth_identity_service import (
            build_auth_identity_runtime_readback,
        )

        db_session = get_session()
        try:
            report = build_auth_identity_runtime_readback(db_session)
        finally:
            db_session.close()

    report["generated_at"] = datetime.now(timezone.utc).isoformat()
    print(
        json.dumps(
            report,
            ensure_ascii=True,
            indent=None if args.compact else 2,
            sort_keys=True,
        )
    )
    if args.require_closed and not report["runtime_closed"]:
        return 2
    if args.strict and not report["canary_ready"]:
        return 1
    return 0


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