"""Zero-dependency LeadProof production delivery client."""

from __future__ import annotations

import json
from typing import Any
from urllib.error import HTTPError
from urllib.parse import urlparse
from urllib.request import Request, urlopen

LEADPROOF_ENDPOINT = "https://leadproof.jessesay.chatgpt.site/api/v1/leads"


class LeadProofError(RuntimeError):
    """A structured error returned by the LeadProof API."""

    def __init__(self, message: str, status: int, details: Any = None) -> None:
        super().__init__(message)
        self.status = status
        self.details = details


def _require_idempotency_key(value: str) -> str:
    key = str(value or "").strip()
    if not key or len(key) > 120:
        raise ValueError("idempotency_key must contain 1 to 120 characters.")
    return key


def _require_destination(value: str) -> str:
    destination = str(value or "").strip()
    parsed = urlparse(destination)
    if parsed.scheme != "https" or not parsed.hostname or parsed.username or parsed.password:
        raise ValueError("destination must be a public HTTPS URL without credentials.")
    return destination


def _decode_response(payload: bytes) -> Any:
    if not payload:
        return None
    text = payload.decode("utf-8", errors="replace")
    try:
        return json.loads(text)
    except json.JSONDecodeError:
        return {"message": text}


class LeadProofClient:
    """Send duplicate-safe lead deliveries to the official LeadProof endpoint."""

    def __init__(self, api_key: str) -> None:
        value = str(api_key or "").strip()
        if not value:
            raise ValueError("A LeadProof API key is required.")
        self._api_key = value

    def deliver(
        self,
        *,
        idempotency_key: str,
        destination: str,
        replay: bool = False,
        timeout: float = 30,
        **lead: Any,
    ) -> Any:
        headers = {
            "Authorization": f"Bearer {self._api_key}",
            "Content-Type": "application/json",
            "Idempotency-Key": _require_idempotency_key(idempotency_key),
        }
        if replay is True:
            headers["X-LeadProof-Replay"] = "true"

        body = json.dumps({**lead, "destination": _require_destination(destination)}).encode("utf-8")
        request = Request(LEADPROOF_ENDPOINT, data=body, headers=headers, method="POST")
        try:
            with urlopen(request, timeout=timeout) as response:
                return _decode_response(response.read())
        except HTTPError as error:
            details = _decode_response(error.read())
            if isinstance(details, dict):
                error_details = details.get("error")
                message = (
                    error_details.get("message")
                    if isinstance(error_details, dict)
                    else details.get("message")
                )
            else:
                message = None
            raise LeadProofError(
                message or f"LeadProof request failed with HTTP {error.code}.",
                error.code,
                details,
            ) from error

    def replay(self, **delivery: Any) -> Any:
        delivery["replay"] = True
        return self.deliver(**delivery)
