"""Human-review decision schema and validation."""

from typing import Optional

DECISIONS = {"confirm", "reject", "unsure", "needs_clarification"}
REASON_CODES = {
    "wrong_cluster_link",
    "same_value_different_representation",
    "not_a_contradiction",
    "missing_evidence",
    "extraction_misread",
    "code_path_not_applicable",
    "duplicate",
    "severity_too_high",
    "severity_too_low",
    "other",
}


def validate_decision(raw: dict) -> Optional[dict]:
    """Normalize a reviewer decision payload, or return None if invalid."""
    if not isinstance(raw, dict):
        return None
    decision = str(raw.get("decision") or "").strip()
    if decision not in DECISIONS:
        return None
    reason_code = raw.get("reason_code")
    if decision == "reject":
        reason_code = str(reason_code or "").strip()
        if reason_code not in REASON_CODES:
            return None
    elif reason_code is not None:
        reason_code = str(reason_code).strip() or None
        if reason_code and reason_code not in REASON_CODES:
            return None
    return {
        "review_item_id": str(raw.get("review_item_id") or "").strip(),
        "decision": decision,
        "reason_code": reason_code,
        "category_correction": raw.get("category_correction"),
        "severity_correction": raw.get("severity_correction"),
        "comment": str(raw.get("comment") or "").strip(),
        "clarification_answer": raw.get("clarification_answer"),
        "reviewed_at": raw.get("reviewed_at"),
    }
