"""Cliente interno Wizard VM112 — mail-bundle (Spec 035 / 043)."""

from __future__ import annotations

import os
from typing import Any

import httpx

VM112_API = os.getenv("VM112_API_URL", "http://10.10.10.112:8090").rstrip("/")
OPS_INTERNAL_TOKEN = os.getenv("OPS_INTERNAL_TOKEN", "")


def configured() -> bool:
    return bool(OPS_INTERNAL_TOKEN)


def provision_mail_bundle(payload: dict[str, Any]) -> dict[str, Any]:
    if not configured():
        return {
            "skipped": True,
            "reason": "OPS_INTERNAL_TOKEN ausente no Desk",
        }
    url = f"{VM112_API}/api/internal/provision/mail-bundle"
    headers = {
        "X-Ops-Internal-Token": OPS_INTERNAL_TOKEN,
        "Content-Type": "application/json",
    }
    with httpx.Client(timeout=120.0) as client:
        res = client.post(url, json=payload, headers=headers)
    if res.status_code == 404:
        return {
            "skipped": True,
            "reason": "endpoint mail-bundle ainda não disponível na VM112",
            "status": 404,
        }
    if res.status_code >= 400:
        raise RuntimeError(f"wizard mail-bundle HTTP {res.status_code}: {res.text[:300]}")
    try:
        body = res.json()
    except Exception:
        body = {"raw": res.text}
    return {
        "provisioned": True,
        "status": res.status_code,
        "response": body,
        "mail_host": body.get("mail_host") or f"mail.{payload.get('domain', '')}",
    }
