from __future__ import annotations

from dataclasses import dataclass
from typing import Any, Mapping


AGENT_FINAL_RESULT_STOP_STATUS = {
    "resolvido": "stop_resolvido_e_finalizado",
    "nao_resolvido": "stop_nao_resolvido",
    "resolvido_outros_assuntos": "stop_outro_assunto",
    "outros_assuntos": "stop_outro_assunto",
    "erro_falha_sistema": "stop_falha_sistema",
    "erro_no_match": "stop_no_match",
}


@dataclass(frozen=True, slots=True)
class AgentFinalStop:
    result_type: str
    status: str
    reason: str
    phase: str = "in_session"


def normalize_agent_result_type(value: Any) -> str:
    return str(value or "").strip().lower()


def stop_status_for_agent_result_type(result_type: Any) -> str:
    return AGENT_FINAL_RESULT_STOP_STATUS.get(normalize_agent_result_type(result_type), "")


def final_stop_from_agent_result(result: Any) -> AgentFinalStop | None:
    if not isinstance(result, Mapping):
        return None

    result_type = normalize_agent_result_type(result.get("type"))
    status = stop_status_for_agent_result_type(result_type)
    if not status:
        return None

    return AgentFinalStop(
        result_type=result_type,
        status=status,
        reason=result_type,
    )
