from app.action_catalog import ACTION_CODES, get_action_config
from app.schemas import ActionDecision, ActionResult


# Apenas normalizações benignas de formato/typo. Códigos legados operacionais
# não são convertidos: se aparecerem, a tarefa vai para revisão.
ACTION_CODE_ALIASES = {
    "SENDO_INVOICE": "SEND_INVOICE",
    "SENDING_INVOICE": "SEND_INVOICE",
}


def normalize_action_code(value: str) -> str:
    code = str(value or "").strip().upper()
    code = ACTION_CODE_ALIASES.get(code, code)
    if code not in ACTION_CODES:
        return "REVIEW_MANUALLY"
    return code


def map_action_decision(decision: ActionDecision) -> ActionResult:
    code = normalize_action_code(decision.action_code)
    config = get_action_config(code)

    note = str(decision.note or "").strip()
    if not note:
        note = config["action"]

    return ActionResult(
        action_code=code,
        route=config["route"],
        action_required=config["action_required"],
        action=config["action"],
        note=note,
        safe_to_post=config["safe_to_post"],
    )
