"""OpenPanel Community bridge client."""

from __future__ import annotations

import os
from typing import Any

import httpx

BRIDGE_URL = os.getenv("OPENPANEL_BRIDGE_URL", "http://10.10.10.123:18087").rstrip("/")
BRIDGE_TOKEN = os.getenv("OPENPANEL_BRIDGE_TOKEN", "")
OPENADMIN_URL = os.getenv("OPENADMIN_URL", "https://admin.openpanel.ligbox.com.br:2087")


def bridge_configured() -> bool:
    return bool(BRIDGE_TOKEN)


def autologin_payload(username: str) -> dict[str, Any]:
    """MVP: devolve URL OpenAdmin + instrução CONNECT (Enterprise futuro)."""
    return {
        "username": username,
        "openadmin_url": OPENADMIN_URL,
        "note": "CONNECT autologin requer OpenPanel Enterprise API — use OpenAdmin manualmente",
        "bridge_configured": bridge_configured(),
    }


def health() -> dict[str, Any]:
    if not bridge_configured():
        return {"ok": False, "reason": "OPENPANEL_BRIDGE_TOKEN ausente"}
    with httpx.Client(timeout=10.0) as client:
        res = client.get(f"{BRIDGE_URL}/api", headers={"Authorization": f"Bearer {BRIDGE_TOKEN}"})
    return {"ok": res.status_code < 400, "status": res.status_code}
