"""Training review state helpers for evolution approval / rollback flow."""

from typing import Any

from src.param_flow import extract_param_map


def build_training_review_state(
    effective_payload: dict[str, Any],
    candidate_value: Any = None,
) -> dict[str, Any]:
    """Build a training review snapshot from effective params and a candidate."""
    effective_payload = effective_payload if isinstance(effective_payload, dict) else {}
    candidate_value = candidate_value if isinstance(candidate_value, dict) else {}
    effective_param_map = extract_param_map(effective_payload)
    offline_params = (
        effective_payload.get("offline_params", {})
        if isinstance(effective_payload.get("offline_params", {}), dict)
        else {}
    )
    training_review_pending = bool(effective_payload.get("review_pending", False)) or bool(
        offline_params.get("review_pending", False)
    )
    return {
        "effective_params": effective_payload,
        "candidate_value": candidate_value,
        "effectiveParamMap": effective_param_map,
        "hasEffectiveParams": bool(effective_param_map),
        "trainingReviewPendingRaw": training_review_pending,
        "review_ready": bool(effective_param_map) and bool(candidate_value.get("ready_for_manual_review", True)),
    }


def public_training_review_state(review_state: dict[str, Any]) -> dict[str, Any]:
    """Extract the public-facing subset of a training review."""
    return {
        "reviewReady": review_state.get("review_ready", False),
        "effectiveParams": review_state.get("effective_params", {}),
        "effectiveParamMap": review_state.get("effectiveParamMap", {}),
        "reviewPending": review_state.get("trainingReviewPendingRaw", False),
    }
