from __future__ import annotations

from typing import Any, Mapping


def _pick_value(payload: Mapping[str, Any] | None, *keys: str) -> str:
    if not isinstance(payload, Mapping):
        return ""

    for key in keys:
        value = payload.get(key)
        if value not in (None, ""):
            return str(value).strip()

    lowered = {str(key).lower(): value for key, value in payload.items()}
    for key in keys:
        value = lowered.get(str(key).lower())
        if value not in (None, ""):
            return str(value).strip()

    return ""


def extract_protocol(
    start_payload: Mapping[str, Any] | None,
    session_data: Mapping[str, Any] | None = None,
) -> str:
    data = start_payload.get("data") if isinstance(start_payload, Mapping) else {}
    if not isinstance(data, Mapping):
        data = {}

    protocol = _pick_value(
        data,
        "protocol_id",
        "protocolId",
        "protocolo",
        "PROTOCOLO",
        "protocol",
        "Protocol",
        "routerCallKey",
        "RouterCallKey",
        "router_call_key",
    )
    if protocol:
        return protocol

    return _pick_value(
        session_data,
        "protocol_id",
        "protocolId",
        "protocolo",
        "PROTOCOLO",
        "protocol",
        "Protocol",
        "routerCallKey",
        "RouterCallKey",
        "router_call_key",
    )
