"""Live status header via StatusAdapter (no GTK)."""

from __future__ import annotations

from datetime import datetime, timezone
from pathlib import Path

from ...core.version import AGENT_MVP_VERSION
from . import UI_SURFACE


def _utc_now_iso() -> str:
    return datetime.now(tz=timezone.utc).replace(microsecond=0).isoformat().replace("+00:00", "Z")


def _orchestra_label(state_value: str, *, lang: str = "en") -> str:
    from ..ui.i18n import translate

    key = {
        "cloud_active": "status.orchestra.cloud_active",
        "local_fallback": "status.orchestra.local_fallback",
        "offline": "status.orchestra.offline",
    }.get(str(state_value or "").strip().lower(), "status.orchestra.offline")
    return translate(lang, key)


def build_live_status(*, config_path: Path | None, lang: str = "en") -> dict[str, object] | None:
    if config_path is None or not config_path.is_file():
        return None
    try:
        from ..orchestra_status_service import probe_orchestra_status
        from ..ui.status_adapter import StatusAdapter

        adapter = StatusAdapter(config_path=config_path)
        dash = adapter.read_dashboard_snapshot()
        devices = adapter.read_devices_snapshot()
        owner = adapter.read_owner_display_snapshot()
        granted, _total = adapter.read_active_ui_grant_counts()
        caps = adapter.read_capability_snapshot()
        root_on = bool(caps.get("root_operations", {}).get("enabled", False))
        paired = bool(dash.get("paired", False))
        connectivity = str(dash.get("connectivity") or dash.get("runtime_state") or "Offline")
        trust = str(dash.get("trust_state") or dash.get("trust_badge") or "Unpaired")
        creds = adapter.read_cloud_probe_credentials()
        orch = probe_orchestra_status(
            device_paired=paired,
            backend_url=creds[0] if creds else None,
            auth_token=creds[1] if creds else None,
            config_path=config_path,
        )
        avatar_mode = "Active" if root_on or granted > 0 else "Inactive"
        return {
            "ok": True,
            "ui_surface": UI_SURFACE,
            "connectivity": connectivity,
            "trust_state": trust,
            "paired": paired,
            "device_id": str(devices.get("device_id") or "") or None,
            "account_email": str(owner.get("owner_email") or "") or None,
            "orchestra_label": _orchestra_label(orch.state.value, lang=lang),
            "orchestra_state": orch.state.value,
            "heartbeat_age_sec": dash.get("heartbeat_age_sec"),
            "backend_base_url": str(dash.get("backend_base_url") or ""),
            "app_version": str(dash.get("app_version") or AGENT_MVP_VERSION),
            "avatar_mode": avatar_mode,
            "active_permissions": int(granted),
            "source": "live",
            "stub": False,
            "phase": "C.2",
            "computed_at": _utc_now_iso(),
        }
    except Exception:
        return None
