"""Track the intelligence route used for the latest Avatar message (console status sync)."""

from __future__ import annotations

from enum import Enum

from .orchestra_status_service import OrchestraStatusSnapshot, OrchestraStatusState


class OrchestraRoutingPath(str, Enum):
    UNKNOWN = "unknown"
    CLOUD_ORCHESTRA = "cloud_orchestra"
    LOCAL_OLLAMA = "local_ollama"
    REGEX = "regex"
    UNAVAILABLE = "unavailable"


_LAST_ROUTING_PATH = OrchestraRoutingPath.UNKNOWN
_LAST_MODEL_LABEL = ""


def record_routing_path(path: str | OrchestraRoutingPath) -> None:
    """Record which intelligence path handled the latest Avatar LLM request."""
    global _LAST_ROUTING_PATH
    if isinstance(path, OrchestraRoutingPath):
        _LAST_ROUTING_PATH = path
        return
    raw = str(path or "").strip().lower()
    try:
        _LAST_ROUTING_PATH = OrchestraRoutingPath(raw)
    except ValueError:
        _LAST_ROUTING_PATH = OrchestraRoutingPath.UNKNOWN


def last_routing_path() -> OrchestraRoutingPath:
    return _LAST_ROUTING_PATH


def record_routing_model(model_label: str) -> None:
    """Record human-readable model name from the latest Orchestra/LLM route."""
    global _LAST_MODEL_LABEL
    _LAST_MODEL_LABEL = str(model_label or "").strip()


def last_routing_model() -> str:
    return _LAST_MODEL_LABEL


def reset_routing_path() -> None:
    global _LAST_ROUTING_PATH, _LAST_MODEL_LABEL
    _LAST_ROUTING_PATH = OrchestraRoutingPath.UNKNOWN
    _LAST_MODEL_LABEL = ""


def resolve_effective_orchestra_state(
    snapshot: OrchestraStatusSnapshot,
    *,
    last_path: OrchestraRoutingPath | None = None,
) -> OrchestraStatusState:
    """Align console indicator with connectivity probes; routing path is diagnostic only."""
    probed = snapshot.state
    if probed == OrchestraStatusState.CLOUD_ACTIVE:
        return OrchestraStatusState.CLOUD_ACTIVE

    path = last_path if last_path is not None else last_routing_path()
    if path == OrchestraRoutingPath.CLOUD_ORCHESTRA:
        if (
            snapshot.cloud_reachable
            and snapshot.cloud_credentials
            and snapshot.orchestra_available
        ):
            return OrchestraStatusState.CLOUD_ACTIVE
        return OrchestraStatusState.LOCAL_FALLBACK

    if path in {OrchestraRoutingPath.LOCAL_OLLAMA, OrchestraRoutingPath.REGEX}:
        if probed == OrchestraStatusState.OFFLINE:
            return OrchestraStatusState.OFFLINE
        return OrchestraStatusState.LOCAL_FALLBACK

    if path == OrchestraRoutingPath.UNAVAILABLE:
        return probed

    return probed
