"""Orchestra intelligence status probing for the desktop agent console."""

from __future__ import annotations

from dataclasses import dataclass
from enum import Enum
import logging
from pathlib import Path
from typing import Any

logger = logging.getLogger(__name__)


class OrchestraStatusState(str, Enum):
    CLOUD_ACTIVE = "cloud_active"
    LOCAL_FALLBACK = "local_fallback"
    OFFLINE = "offline"


@dataclass(frozen=True)
class OrchestraStatusSnapshot:
    state: OrchestraStatusState
    cloud_reachable: bool = False
    cloud_credentials: bool = False
    account_verified: bool = False
    orchestra_available: bool = False
    saas_cloud_allowed: bool = False
    ollama_reachable: bool = False
    device_paired: bool = False
    detail: str = ""
    fallback_reason: str = ""


def _saas_cloud_providers_allowed(saas: dict[str, Any] | None) -> bool:
    if not isinstance(saas, dict) or not saas:
        return False
    capabilities = saas.get("capabilities")
    if isinstance(capabilities, list):
        for row in capabilities:
            if not isinstance(row, dict):
                continue
            if str(row.get("id") or "").strip() == "cloud_providers":
                return bool(row.get("allowed"))
    allowed = saas.get("allowed_providers")
    if isinstance(allowed, list):
        for provider_id in allowed:
            if str(provider_id or "").strip().lower() not in {"", "ollama_local"}:
                return True
    return False


def resolve_orchestra_status_state(
    *,
    cloud_reachable: bool,
    cloud_credentials: bool,
    orchestra_available: bool,
    ollama_reachable: bool,
    device_paired: bool,
    saas_cloud_allowed: bool = False,
) -> OrchestraStatusState:
    """Pure state machine for orchestra intelligence indicator."""
    cloud_viable = cloud_reachable and cloud_credentials and (orchestra_available or saas_cloud_allowed)
    if cloud_viable:
        return OrchestraStatusState.CLOUD_ACTIVE
    if device_paired or ollama_reachable:
        return OrchestraStatusState.LOCAL_FALLBACK
    return OrchestraStatusState.OFFLINE


def resolve_orchestra_fallback_reason(
    *,
    state: OrchestraStatusState,
    cloud_credentials: bool,
    cloud_reachable: bool,
    account_verified: bool,
    orchestra_available: bool,
    saas_cloud_allowed: bool,
    detail: str,
) -> str:
    if state == OrchestraStatusState.CLOUD_ACTIVE:
        return ""
    if not cloud_credentials:
        return "not_connected"
    if not cloud_reachable:
        return "backend_unreachable"
    if not account_verified:
        return "account_unverified"
    lowered = str(detail or "").strip().lower()
    if "orchestra_disabled" in lowered or "avatar_provider_orchestra_disabled" in lowered:
        return "orchestra_disabled"
    if "capability_denied" in lowered or "cloud_providers" in lowered:
        return "entitlement_denied"
    if not saas_cloud_allowed and not orchestra_available:
        return "entitlement_denied"
    if detail:
        return str(detail)
    return "probe_failed"


def _probe_ollama_reachable() -> bool:
    try:
        from iuve_connect_agents.shared.feature_flags import avatar_local_ollama_reachable

        return avatar_local_ollama_reachable()
    except Exception:
        return False


def probe_orchestra_status(
    *,
    device_paired: bool = False,
    backend_url: str | None = None,
    auth_token: str | None = None,
    config_path: str | Path | None = None,
) -> OrchestraStatusSnapshot:
    """Probe cloud orchestra, account, and optional local Ollama for console status."""
    cloud_credentials = False
    cloud_reachable = False
    account_verified = False
    orchestra_available = False
    saas_cloud_allowed = False
    detail = ""

    creds: tuple[str, str] | None = None
    explicit_backend = str(backend_url or "").strip().rstrip("/")
    explicit_token = str(auth_token or "").strip()
    if explicit_backend and explicit_token:
        creds = (explicit_backend, explicit_token)
    else:
        try:
            from iuve_connect_agents.shared.avatar_llm_cloud import load_desktop_cloud_credentials

            creds = load_desktop_cloud_credentials(config_path=config_path)
        except Exception:
            creds = None

    if creds:
        cloud_credentials = True
        backend_url_value, auth_token_value = creds
        try:
            from iuve_connect_agents.core.api_client import BackendAuthRequiredError, PassiveApiClient

            client = PassiveApiClient(base_url=backend_url_value)
            cloud_reachable = client.probe_backend_health(timeout=5)
            if cloud_reachable:
                try:
                    profile = client.get_agent_profile(auth_token=auth_token_value)
                    account_verified = bool(profile)
                    if account_verified:
                        saas = client.get_saas_context(auth_token=auth_token_value)
                        if not saas:
                            detail = "saas_context_empty"
                        saas_cloud_allowed = _saas_cloud_providers_allowed(
                            saas if isinstance(saas, dict) else None
                        )
                        probe_ok, probe_reason = client.probe_orchestra_endpoint(
                            auth_token=auth_token_value,
                            timeout=8,
                        )
                        orchestra_available = bool(probe_ok)
                        if detail == "":
                            detail = probe_reason
                        if not probe_ok and saas_cloud_allowed:
                            detail = probe_reason or "orchestra_probe_failed_saas_ok"
                except BackendAuthRequiredError as exc:
                    detail = str(exc or "auth_failed")
                except Exception as exc:
                    detail = str(exc or "account_probe_failed")
            else:
                detail = "backend_unreachable"
        except Exception as exc:
            detail = str(exc or "cloud_probe_failed")
            logger.debug("orchestra_status_cloud_probe_failed error=%s", exc)
    else:
        detail = "not_connected"

    ollama_reachable = _probe_ollama_reachable()
    orchestra_effective = orchestra_available or (account_verified and saas_cloud_allowed and cloud_reachable)
    state = resolve_orchestra_status_state(
        cloud_reachable=cloud_reachable,
        cloud_credentials=cloud_credentials,
        orchestra_available=orchestra_effective,
        ollama_reachable=ollama_reachable,
        device_paired=bool(device_paired),
        saas_cloud_allowed=saas_cloud_allowed and account_verified and cloud_reachable,
    )
    fallback_reason = resolve_orchestra_fallback_reason(
        state=state,
        cloud_credentials=cloud_credentials,
        cloud_reachable=cloud_reachable,
        account_verified=account_verified,
        orchestra_available=orchestra_effective,
        saas_cloud_allowed=saas_cloud_allowed,
        detail=detail,
    )
    return OrchestraStatusSnapshot(
        state=state,
        cloud_reachable=cloud_reachable,
        cloud_credentials=cloud_credentials,
        account_verified=account_verified,
        orchestra_available=orchestra_effective,
        saas_cloud_allowed=saas_cloud_allowed,
        ollama_reachable=ollama_reachable,
        device_paired=bool(device_paired),
        detail=detail,
        fallback_reason=fallback_reason,
    )
