"""Cloud orchestra LLM access for paired desktop agents (iuve.eu backend API)."""

from __future__ import annotations

import json
import logging
from pathlib import Path
from typing import Any

logger = logging.getLogger(__name__)

_LAST_UNAVAILABLE_REASON = "unknown"

_DEFAULT_CONFIG_PATH = Path.home() / ".config" / "iuve-connect-agent" / "desktop-config.json"


def cloud_llm_unavailable_reason() -> str:
    """Best-effort reason for the latest cloud LLM failure (for UI messaging)."""
    return _LAST_UNAVAILABLE_REASON


def _set_unavailable_reason(reason: str) -> None:
    global _LAST_UNAVAILABLE_REASON
    _LAST_UNAVAILABLE_REASON = str(reason or "unknown").strip() or "unknown"


def load_desktop_cloud_credentials(
    config_path: str | Path | None = None,
) -> tuple[str, str] | None:
    """Return (backend_base_url, device_auth_token) when the agent is paired."""
    cfg_path = Path(config_path).expanduser() if config_path else _DEFAULT_CONFIG_PATH
    if not cfg_path.exists():
        _set_unavailable_reason("not_connected")
        return None
    try:
        data = json.loads(cfg_path.read_text(encoding="utf-8"))
    except (OSError, json.JSONDecodeError):
        _set_unavailable_reason("not_connected")
        return None

    config_block = dict(data.get("agent", data))
    backend_url = str(config_block.get("backend_base_url") or "").strip().rstrip("/")
    if not backend_url:
        _set_unavailable_reason("not_connected")
        return None

    storage_path = Path(
        data.get("storage_path") or Path.home() / ".config" / "iuve-connect-agent" / "desktop-state.json"
    )
    try:
        from iuve_connect_agents.core.storage import JsonFileSecureStorage

        state = JsonFileSecureStorage(storage_path).load_state()
    except Exception:
        state = None
    if state is None:
        _set_unavailable_reason("not_connected")
        return None

    auth_token = str(getattr(state, "device_auth_token", "") or "").strip()
    if not auth_token:
        _set_unavailable_reason("not_connected")
        return None
    return backend_url, auth_token


def cloud_llm_credentials_available() -> bool:
    return load_desktop_cloud_credentials() is not None


def _record_cloud_route_metadata(payload: dict[str, Any] | None) -> None:
    """Persist orchestra route + model label for console chip/timeline."""
    if not isinstance(payload, dict):
        return
    try:
        from iuve_connect_agents.desktop.orchestra_routing_tracker import (
            OrchestraRoutingPath,
            record_routing_model,
            record_routing_path,
        )
        from iuve_connect_agents.desktop.ui.avatar_execution_status import parse_planner_model_label

        record_routing_path(OrchestraRoutingPath.CLOUD_ORCHESTRA)
        provider_id = str(payload.get("provider_id") or "").strip()
        sub_model = str(payload.get("sub_model") or payload.get("model") or "").strip()
        if sub_model:
            record_routing_model(sub_model)
        elif provider_id:
            record_routing_model(parse_planner_model_label(f"orchestra_{provider_id}"))
    except ImportError:
        pass


def request_cloud_intent_classify(text: str, *, trust_state: str = "") -> dict[str, Any] | None:
    """Call backend cloud orchestra intent classifier; None when unavailable."""
    creds = load_desktop_cloud_credentials()
    if not creds:
        return None
    backend_url, auth_token = creds
    query = str(text or "").strip()
    if not query:
        return None

    try:
        from iuve_connect_agents.core.api_client import BackendAuthRequiredError, PassiveApiClient

        payload = PassiveApiClient(base_url=backend_url).request_avatar_llm_intent(
            auth_token=auth_token,
            text=query,
            trust_state=str(trust_state or ""),
        )
    except BackendAuthRequiredError:
        _set_unavailable_reason("not_connected")
        logger.warning("avatar_cloud_intent_auth_required")
        return None
    except Exception as exc:
        message = str(exc).lower()
        if "backend_unreachable" in message or "urlerror" in message:
            _set_unavailable_reason("network")
        elif "http_402" in message or "http_403" in message:
            _set_unavailable_reason("tariff")
        elif "http_503" in message or "orchestra" in message:
            _set_unavailable_reason("cloud_down")
        else:
            _set_unavailable_reason("cloud_down")
        logger.warning("avatar_cloud_intent_failed error=%s", exc)
        return None

    if not isinstance(payload, dict) or not payload.get("ok"):
        detail = str((payload or {}).get("error") or "").strip().lower()
        if detail in {"invalid_device_auth_token", "missing_device_auth_token", "device_revoked"}:
            _set_unavailable_reason("not_connected")
        elif detail in {"avatar_provider_orchestra_disabled", "orchestra_disabled"}:
            _set_unavailable_reason("cloud_down")
        elif "limit" in detail or "tariff" in detail or "plan" in detail:
            _set_unavailable_reason("tariff")
        else:
            _set_unavailable_reason("cloud_down")
        return None

    _set_unavailable_reason("ok")
    _record_cloud_route_metadata(payload)
    return payload


def request_cloud_advisory(text: str, *, trust_state: str = "") -> str | None:
    """Call backend cloud orchestra for advisory answer; None when unavailable."""
    creds = load_desktop_cloud_credentials()
    if not creds:
        return None
    backend_url, auth_token = creds
    query = str(text or "").strip()
    if not query:
        return None

    try:
        from iuve_connect_agents.core.api_client import BackendAuthRequiredError, PassiveApiClient

        payload = PassiveApiClient(base_url=backend_url).request_avatar_llm_advisory(
            auth_token=auth_token,
            text=query,
            trust_state=str(trust_state or ""),
        )
    except BackendAuthRequiredError:
        _set_unavailable_reason("not_connected")
        return None
    except Exception as exc:
        message = str(exc).lower()
        if "backend_unreachable" in message:
            _set_unavailable_reason("network")
        elif "http_402" in message or "http_403" in message:
            _set_unavailable_reason("tariff")
        else:
            _set_unavailable_reason("cloud_down")
        logger.warning("avatar_cloud_advisory_failed error=%s", exc)
        return None

    if not isinstance(payload, dict) or not payload.get("ok"):
        detail = str((payload or {}).get("error") or "").strip().lower()
        if detail in {"invalid_device_auth_token", "missing_device_auth_token"}:
            _set_unavailable_reason("not_connected")
        elif "limit" in detail or "tariff" in detail:
            _set_unavailable_reason("tariff")
        else:
            _set_unavailable_reason("cloud_down")
        return None

    answer = str(payload.get("answer") or "").strip()
    if answer:
        _set_unavailable_reason("ok")
        _record_cloud_route_metadata(payload)
        return answer
    _set_unavailable_reason("cloud_down")
    return None
