"""AI Providers admin panel helpers for Security page."""

from __future__ import annotations

import webbrowser
from typing import Any, Callable


def format_provider_account_label(t: Callable[[str], str], status: str, connected: bool) -> str:
    cleaned = str(status or "").strip().lower()
    if connected or cleaned == "connected":
        return t("ai_providers.account.connected")
    if cleaned == "pending":
        return t("ai_providers.account.pending")
    return t("ai_providers.account.not_connected")


def format_provider_online_label(t: Callable[[str], str], availability: str) -> str:
    if str(availability or "").strip().lower() == "online":
        return t("ai_providers.status.online")
    return t("ai_providers.status.offline")


def format_connection_hint_label(t: Callable[[str], str], hint: str) -> str:
    cleaned = str(hint or "").strip()
    if not cleaned:
        return ""
    if cleaned.startswith("needs_admin_api_key:"):
        setting_key = cleaned.split(":", 1)[1].strip()
        return t("ai_providers.hint.needs_admin_api_key").format(setting_key=setting_key)
    key = f"ai_providers.hint.{cleaned}"
    translated = t(key)
    if translated != key:
        return translated
    return cleaned


def format_honesty_label(t: Callable[[str], str], honesty: str) -> str:
    cleaned = str(honesty or "").strip()
    if not cleaned:
        return ""
    key = f"ai_providers.honesty.{cleaned}"
    translated = t(key)
    if translated != key:
        return translated
    return cleaned


def provider_connect_action_allowed(provider: dict[str, Any]) -> bool:
    if bool(provider.get("is_local")):
        return False
    if bool(provider.get("account_connected")):
        return False
    mode = str(provider.get("connection_mode") or "").strip().lower()
    hint = str(provider.get("connection_hint") or "").strip().lower()
    if mode == "surface_only":
        return False
    if hint.startswith("needs_admin_api_key"):
        return False
    if hint == "agent_unavailable":
        return False
    return str(provider.get("account_status") or "").strip().lower() in {
        "",
        "not_connected",
        "disconnected",
        "error",
    }


def provider_complete_login_allowed(provider: dict[str, Any]) -> bool:
    return (
        str(provider.get("account_status") or "").strip().lower() == "pending"
        and str(provider.get("connection_hint") or "").strip().lower() == "complete_browser_login"
    )


def open_official_url(url: str) -> None:
    cleaned = str(url or "").strip()
    if cleaned.startswith("https://"):
        webbrowser.open(cleaned)


def provider_row_summary(provider: dict[str, Any], *, t: Callable[[str], str] | None = None) -> str:
    caps = provider.get("capabilities") or []
    if isinstance(caps, list):
        cap_text = ", ".join(str(c) for c in caps[:4])
        if len(caps) > 4:
            cap_text += "…"
    else:
        cap_text = "-"
    health = provider.get("health") if isinstance(provider.get("health"), dict) else {}
    honesty = str(provider.get("honesty") or "").strip()
    executor = provider.get("executor_supported")
    model = str(provider.get("model") or "").strip()
    sync = str(provider.get("sync_source") or "").strip()
    parts = [
        f"cost={provider.get('cost_level', '-')}",
        f"priority={provider.get('priority', '-')}",
        f"caps={cap_text}",
    ]
    if model:
        parts.append(f"model={model}")
    if sync:
        parts.append(f"sync={sync}")
    if honesty:
        honesty_text = format_honesty_label(t, honesty) if t is not None else honesty
        parts.append(f"honesty={honesty_text}")
    elif executor is False:
        parts.append("honesty=no_orchestra_executor")
    latency = health.get("latency_ms")
    if latency not in (None, "", 0, 0.0):
        parts.append(f"latency={latency}ms")
    hint = str(provider.get("connection_hint") or "").strip()
    if hint and t is not None:
        hint_text = format_connection_hint_label(t, hint)
        if hint_text:
            parts.append(hint_text)
    return " ".join(parts)


def normalize_provider_rows(payload: Any) -> list[dict[str, Any]]:
    """Parse server list payload into provider dicts (client sync helper)."""
    if isinstance(payload, list):
        rows = payload
    elif isinstance(payload, dict):
        rows = payload.get("providers") or []
    else:
        rows = []
    out: list[dict[str, Any]] = []
    for row in rows:
        if not isinstance(row, dict):
            continue
        provider_id = str(row.get("provider_id") or "").strip()
        if not provider_id:
            continue
        health = row.get("health") if isinstance(row.get("health"), dict) else {}
        availability = str(health.get("availability") or "offline").strip().lower()
        if availability not in {"online", "offline", "degraded"}:
            availability = "offline"
        configured = bool(row.get("configured", availability == "online"))
        out.append(
            {
                **row,
                "provider_id": provider_id,
                "name": str(row.get("name") or provider_id),
                "configured": configured,
                "executor_supported": bool(row.get("executor_supported", False)),
                "honesty": str(row.get("honesty") or ""),
                "connection_mode": str(row.get("connection_mode") or ""),
                "connection_hint": str(row.get("connection_hint") or ""),
                "health": {
                    **health,
                    "availability": availability if configured else "offline",
                },
            }
        )
    return out
