"""Self-hosted calling platform provider (platform/services/*).

Talks to scheduler_service over HMAC-signed HTTP (see ai_calls.security /
platform/shared/auth.py — the two implementations mirror each other):

    POST {AI_PLATFORM_URL}/v1/calls              — enqueue the outbound call
    POST {AI_PLATFORM_URL}/v1/calls/{id}/cancel  — best-effort cancel

The platform reports progress to the three ATS callbacks
(webhook/transcript/completed), signing each request with X-ATS-Signature."""

import json
import logging

import httpx
from django.conf import settings

from ..security import sign_headers
from .base import BaseProvider

logger = logging.getLogger(__name__)


class SelfHostedProvider(BaseProvider):
    name = "selfhosted"

    def _post(self, path, payload):
        body = json.dumps(payload).encode()
        headers = {"Content-Type": "application/json"}
        headers.update(sign_headers(settings.AI_PLATFORM_SIGNING_SECRET, body))
        res = httpx.post(
            f"{settings.AI_PLATFORM_URL.rstrip('/')}{path}",
            content=body, headers=headers, timeout=15,
        )
        res.raise_for_status()
        return res.json() if res.content else {}

    def start_call(self, ai_call):
        payload = {
            "call_id": ai_call.id,
            "phone": ai_call.agent_variables.get("phone"),
            "lang_hint": "en",
            "variables": ai_call.agent_variables,
            "max_duration_s": 7 * 60,
            "callback_url": f"{settings.PUBLIC_BASE_URL}/api/v1/ai-calls",
        }
        logger.info("[PLATFORM] Enqueue call for AICall %s -> %s/v1/calls",
                    ai_call.id, settings.AI_PLATFORM_URL)
        data = self._post("/v1/calls", payload)
        call_id = data.get("call_id") or data.get("id")
        if not call_id:
            raise RuntimeError(f"Platform returned no call id: {data}")
        return str(call_id)

    def cancel_call(self, ai_call):
        if not ai_call.provider_call_id:
            return False
        try:
            self._post(f"/v1/calls/{ai_call.provider_call_id}/cancel", {})
            return True
        except httpx.HTTPError as e:
            logger.warning("[PLATFORM] Cancel failed for %s: %s", ai_call.provider_call_id, e)
            return False
