"""Phase D6: CLI to verify audit log integrity (HMAC + hash chain).

Usage:
  python -m aurora_lens.scripts.verify_audit --path audit.jsonl [--n 1000] [--key $KEY]
  python -m aurora_lens.scripts.verify_audit --path audit.jsonl --keys "$OLD_KEY,$NEW_KEY"

D4 multi-key: use --keys for logs spanning key rotation. Tries each key per entry.
"""

from __future__ import annotations

import argparse
import os
import sys
from pathlib import Path

from aurora_lens.govern.audit_io import (
    verify_audit_entries,
    verify_chain,
    verify_forensic_state_hash,
)


def _parse_keys(key: str | None, keys: str | None, env_key: str, env_keys: str) -> list[bytes]:
    """Build list of signing keys from --key, --keys, and env vars."""
    result: list[bytes] = []
    single = (key or os.environ.get(env_key, "")).strip()
    if single:
        result.append(single.encode("utf-8"))
    multi = (keys or os.environ.get(env_keys, "")).strip()
    if multi:
        for k in multi.split(","):
            k = k.strip()
            if k and k.encode("utf-8") not in result:
                result.append(k.encode("utf-8"))
    return result


def main() -> int:
    parser = argparse.ArgumentParser(
        description="Verify audit log integrity (HMAC + hash chain).",
    )
    parser.add_argument(
        "--path",
        required=True,
        help="Path to audit JSONL file",
    )
    parser.add_argument(
        "--n",
        type=int,
        default=1000,
        help="Number of last entries to verify (default: 1000)",
    )
    parser.add_argument(
        "--key",
        default=None,
        help="Signing key for HMAC. Default: AURORA_LENS_AUDIT_SIGNING_KEY env",
    )
    parser.add_argument(
        "--keys",
        default=None,
        help="Comma-separated keys for logs spanning rotation (D4). AURORA_LENS_AUDIT_SIGNING_KEYS env",
    )
    parser.add_argument(
        "--no-replay",
        action="store_true",
        help="Skip replay verification (state_hash from pef_snapshot)",
    )
    args = parser.parse_args()

    path = Path(args.path)
    if not path.exists():
        print(f"Error: file not found: {path}", file=sys.stderr)
        return 1

    signing_keys = _parse_keys(
        args.key, args.keys,
        "AURORA_LENS_AUDIT_SIGNING_KEY", "AURORA_LENS_AUDIT_SIGNING_KEYS",
    )
    if not signing_keys:
        print("Error: signing key required (--key, --keys, or env)", file=sys.stderr)
        return 1

    hmac_ok, hmac_entries, first_failed = verify_audit_entries(
        path, args.n, signing_keys=signing_keys
    )
    chain_ok, chain_entries, first_break_idx, reason = verify_chain(
        path, args.n, signing_keys=signing_keys
    )
    replay_ok = True
    replay_checked = 0
    replay_fail_idx = None
    replay_reason = None
    if not args.no_replay:
        replay_ok, replay_checked, replay_fail_idx, replay_reason = verify_forensic_state_hash(
            path, args.n
        )

    if hmac_ok and chain_ok and replay_ok:
        parts = [f"{chain_entries} entries verified (HMAC + chain)"]
        if replay_checked > 0:
            parts.append(f"{replay_checked} forensic state_hash replayed")
        print(f"OK: {', '.join(parts)}")
        return 0

    if not hmac_ok:
        print(f"FAIL: HMAC verification failed at entry (trace_id: {first_failed})", file=sys.stderr)
        return 1
    if not chain_ok:
        print(f"FAIL: chain break at index {first_break_idx} ({reason})", file=sys.stderr)
        return 1
    if not replay_ok:
        print(
            f"FAIL: replay verification failed at index {replay_fail_idx} ({replay_reason})",
            file=sys.stderr,
        )
        return 1
    return 1


if __name__ == "__main__":
    sys.exit(main())
