"""CLI helpers for L2 memory audit surfaces."""

from __future__ import annotations

import argparse
from typing import Any

from brain.v5.failure_mode_audit import audit_failure_mode_coverage
from dataclasses import asdict

from brain.v5.failure_mode_review import build_failure_mode_review_packet, request_failure_mode_review_checkpoint
from brain.v5.memory_audit import audit_l2_memory_context
from brain.v5.public_surfaces import require_valid_public_surface


def add_memory_parser(sp: argparse._SubParsersAction) -> None:
    memory = sp.add_parser("memory")
    ms = memory.add_subparsers(dest="memory_command", required=True)
    audit = ms.add_parser("audit")
    audit.add_argument("--claim", required=True, dest="claim_id")
    failure_modes = ms.add_parser("failure-modes")
    failure_modes.add_argument("--claim", required=True, dest="claim_id")
    review = ms.add_parser("failure-mode-review")
    review.add_argument("--claim", required=True, dest="claim_id")
    review_checkpoint = ms.add_parser("request-failure-mode-review")
    review_checkpoint.add_argument("--claim", required=True, dest="claim_id")


def dispatch_memory_command(args: argparse.Namespace, ws: Any) -> dict[str, Any]:
    if args.memory_command == "audit":
        return require_valid_public_surface(
            "l2_memory_audit",
            audit_l2_memory_context(ws, claim_id=args.claim_id),
        )
    if args.memory_command == "failure-modes":
        return require_valid_public_surface(
            "failure_mode_audit",
            audit_failure_mode_coverage(ws, claim_id=args.claim_id),
        )
    if args.memory_command == "failure-mode-review":
        return require_valid_public_surface(
            "failure_mode_review_packet",
            build_failure_mode_review_packet(ws, claim_id=args.claim_id),
        )
    if args.memory_command == "request-failure-mode-review":
        return require_valid_public_surface(
            "human_checkpoint_record",
            {"ok": True, **asdict(request_failure_mode_review_checkpoint(ws, claim_id=args.claim_id))},
        )
    raise SystemExit(f"unsupported memory command: {args.memory_command}")
