"""
mizan_debates: the Python client for the Mizan API (https://mizandebates.com/api/).
Order AI debates (both sides of a question, with audio, transcript and video) from your app.
No dependencies beyond Python 3.9+.

    from mizan_debates import Mizan

    mizan = Mizan("mz_live_...")                      # or set MIZAN_API_KEY
    debate = mizan.create_debate("Is tea better than coffee?", webhook_url="https://example.com/hooks/mizan")
    debate = mizan.wait_for_debate(debate["id"])     # or wait for the webhook
    print(debate["result"]["page_url"], debate["result"]["audio_url"])

Webhooks (in your web framework, with the RAW request body):

    from mizan_debates import verify_webhook
    event = verify_webhook(raw_body, request.headers["Mizan-Signature"], "whsec_mz_...")
    if event["type"] == "debate.delivered": ...
"""

import hashlib
import hmac
import json
import os
import time
import urllib.error
import urllib.request
import uuid

__version__ = "1.0.0"
__all__ = ["Mizan", "MizanError", "verify_webhook", "WebhookError"]

DEFAULT_BASE_URL = "https://api.mizandebates.com"


class MizanError(Exception):
    """An error answer from the API. `code` is stable (e.g. insufficient_balance); see the guide."""

    def __init__(self, status, code, message):
        super().__init__(f"{status} {code}: {message}")
        self.status, self.code, self.message = status, code, message


class Mizan:
    def __init__(self, api_key=None, base_url=None, timeout=120, retries=2):
        self.api_key = api_key or os.environ.get("MIZAN_API_KEY", "")
        if not self.api_key:
            raise ValueError("Pass your API key, or set MIZAN_API_KEY (create one at https://mizandebates.com/api/).")
        self.base_url = (base_url or os.environ.get("MIZAN_API_URL") or DEFAULT_BASE_URL).rstrip("/")
        self.timeout, self.retries = timeout, retries

    # --- the API ---------------------------------------------------------------------------

    def create_debate(self, topic, lang="en", dialect="msa", positions=None, visibility="private",
                      webhook_url=None, reference=None, idempotency_key=None):
        """Order a debate (charged from your API balance). Returns the debate, status "queued".
        positions: [{"title": ..., "description": ...}, {...}] or None to let Mizan choose.
        A retry after a network error reuses the same Idempotency-Key, so you're never charged twice."""
        body = {"topic": topic, "lang": lang, "dialect": dialect, "visibility": visibility}
        for name, value in (("positions", positions), ("webhook_url", webhook_url), ("reference", reference)):
            if value is not None:
                body[name] = value
        return self._call("POST", "/v1/debates", body, idempotency_key=idempotency_key or str(uuid.uuid4()))

    def get_debate(self, debate_id):
        return self._call("GET", f"/v1/debates/{debate_id}")

    def get_transcript(self, debate_id):
        """A delivered debate as JSON: topic, debaters and every turn, round by round."""
        return self._call("GET", f"/v1/debates/{debate_id}/transcript")

    def list_debates(self, limit=10):
        return self._call("GET", f"/v1/debates?limit={int(limit)}")["data"]

    def suggest_positions(self, topic, lang="en", dialect="msa"):
        """The two sides Mizan would argue (free). Edit them and pass them to create_debate."""
        return self._call("POST", "/v1/positions", {"topic": topic, "lang": lang, "dialect": dialect})["positions"]

    def balance(self):
        return self._call("GET", "/v1/balance")

    def usage(self):
        return self._call("GET", "/v1/usage")

    def wait_for_debate(self, debate_id, timeout=1200, interval=15):
        """Check every `interval` seconds until the debate is delivered or failed (about 5–10 minutes)."""
        deadline = time.time() + timeout
        while True:
            debate = self.get_debate(debate_id)
            if debate["status"] in ("delivered", "failed") or time.time() > deadline:
                return debate
            time.sleep(interval)

    # --- HTTP ------------------------------------------------------------------------------

    def _call(self, method, path, body=None, idempotency_key=None):
        headers = {"Authorization": f"Bearer {self.api_key}", "Accept": "application/json",
                   "User-Agent": f"mizan-debates-python/{__version__}"}
        data = None
        if body is not None:
            data = json.dumps(body).encode("utf-8")
            headers["Content-Type"] = "application/json"
        if idempotency_key:
            headers["Idempotency-Key"] = idempotency_key
        for attempt in range(self.retries + 1):
            request = urllib.request.Request(self.base_url + path, data=data, headers=headers, method=method)
            try:
                with urllib.request.urlopen(request, timeout=self.timeout) as r:
                    return json.loads(r.read().decode("utf-8"))
            except urllib.error.HTTPError as e:
                try:
                    err = json.loads(e.read().decode("utf-8")).get("error", {})
                except ValueError:
                    err = {}
                retry = e.code in (502, 503, 504) and attempt < self.retries
                if not retry:
                    raise MizanError(e.code, err.get("code", "error"), err.get("message", e.reason)) from None
            except (urllib.error.URLError, TimeoutError):
                if attempt >= self.retries:
                    raise
            time.sleep(2 ** attempt * 2)
        raise MizanError(503, "try_again", "No answer from the Mizan API")   # not reached: the last try returns or raises


class WebhookError(Exception):
    pass


def verify_webhook(body, signature_header, secret, tolerance=300):
    """Check a webhook really comes from Mizan and is recent; returns the event (a dict).
    body: the raw bytes of the request. signature_header: the Mizan-Signature header."""
    if isinstance(body, str):
        body = body.encode("utf-8")
    parts = [p.split("=", 1) for p in (signature_header or "").split(",") if "=" in p]
    timestamp = next((v for k, v in parts if k == "t"), "")
    signatures = [v for k, v in parts if k == "v1"]
    if not timestamp.isdigit() or not signatures:
        raise WebhookError("Malformed Mizan-Signature header")
    expected = hmac.new(secret.encode(), f"{timestamp}.".encode() + body, hashlib.sha256).hexdigest()
    if not any(hmac.compare_digest(expected, s) for s in signatures):
        raise WebhookError("Signature mismatch")
    if abs(time.time() - int(timestamp)) > tolerance:
        raise WebhookError("Webhook too old")
    return json.loads(body.decode("utf-8"))
