"""BounceZero - official Python client (single file, standard library only).

Usage:
    from bouncezero import BounceZero

    client = BounceZero("bz_live_...")
    result = client.verify("someone@example.com")
    print(result["classification"], result["score"])  # classification: "valid" | "invalid"
    print(result["metadata"]["internal_classification"])  # verified, catch_all, unknown, ...

Docs: https://docs.bouncezero.io
"""
from __future__ import annotations

import hashlib
import hmac
import json
import time
import urllib.error
import urllib.parse
import urllib.request

__version__ = "0.1.1"

DEFAULT_BASE_URL = "https://app.bouncezero.io"

# Bulk job statuses after which the job will not progress further. Anything else
# (queued, processing, interrupted, resuming, finalizing, ...) is still in flight:
# "interrupted" jobs are resumed automatically by the server.
TERMINAL_BULK_STATUSES = frozenset({"completed", "failed", "stopped", "credits_exhausted"})


class BounceZeroError(Exception):
    """Base error. `.status_code` and `.payload` carry the HTTP context."""

    def __init__(self, message, status_code=None, payload=None):
        super().__init__(message)
        self.status_code = status_code
        self.payload = payload or {}


class AuthenticationError(BounceZeroError):
    """401/403 - missing, invalid, disabled, or insufficiently privileged API key."""


class InsufficientCreditsError(BounceZeroError):
    """402 - not enough credits for this operation."""


class NotFoundError(BounceZeroError):
    """404 - resource (e.g. bulk job) not found."""


class RateLimitError(BounceZeroError):
    """429 - plan rate limit exceeded. `.retry_after` holds seconds if the server sent it."""

    def __init__(self, message, status_code=None, payload=None, retry_after=None):
        super().__init__(message, status_code, payload)
        self.retry_after = retry_after


class BounceZero:
    """Client for the BounceZero email verification API."""

    def __init__(self, api_key, base_url=DEFAULT_BASE_URL, timeout=60, max_retries=2):
        if not api_key:
            raise ValueError("api_key is required")
        self.api_key = api_key
        self.base_url = base_url.rstrip("/")
        self.timeout = timeout
        self.max_retries = max_retries

    # ── verification ──────────────────────────────────────────────────────
    def verify(self, email, depth="standard"):
        """Verify one address. depth: 'standard' | 'deep' | 'ultra'."""
        return self._request("POST", "/api/v1/verify", {"email": email, "depth": depth})

    def verify_batch(self, emails):
        """Synchronously verify up to 100 addresses in one call."""
        return self._request("POST", "/api/v1/verify/batch", {"emails": list(emails)})

    def verify_bulk(self, emails, idempotency_key=None):
        """Submit an async bulk job. Pass idempotency_key to make retries safe -
        replaying the same key returns the original job instead of re-charging."""
        headers = {"Idempotency-Key": idempotency_key} if idempotency_key else None
        return self._request("POST", "/api/v1/verify/bulk", {"emails": list(emails)}, headers=headers)

    def bulk_status(self, job_id):
        return self._request("GET", f"/api/v1/verify/bulk/{job_id}/status")

    def bulk_results(self, job_id, limit=1000, offset=0):
        return self._request(
            "GET", f"/api/v1/verify/bulk/{job_id}/results?limit={int(limit)}&offset={int(offset)}"
        )

    def bulk_download(self, job_id):
        """Download completed job results as CSV bytes."""
        return self._request("GET", f"/api/v1/verify/bulk/{job_id}/download", raw=True)

    def wait_for_bulk(self, job_id, poll_interval=5.0, timeout=3600.0):
        """Poll until the job reaches a terminal status (completed, failed, stopped,
        credits_exhausted). Returns the final status payload. "interrupted" is not
        terminal: the server resumes those jobs automatically, so polling continues."""
        deadline = time.monotonic() + timeout
        while True:
            status = self.bulk_status(job_id)
            if status.get("status") in TERMINAL_BULK_STATUSES:
                return status
            if time.monotonic() >= deadline:
                raise BounceZeroError(f"Timed out waiting for bulk job {job_id}")
            time.sleep(poll_interval)

    # ── intelligence ──────────────────────────────────────────────────────
    def domain(self, domain):
        """Domain-level intelligence (MX, provider, catch-all status, ...)."""
        return self._request("GET", f"/api/v1/domain/{urllib.parse.quote(domain)}")

    def analyze_list(self, emails):
        """Free pre-flight quality analysis of an email list (no verification)."""
        return self._request("POST", "/api/v1/analyze/list", {"emails": list(emails)})

    # ── webhooks ──────────────────────────────────────────────────────────
    @staticmethod
    def verify_webhook_signature(raw_body, signature_header, signing_secret):
        """Return True if an X-BounceZero-Signature header matches the raw request body.

        Always verify with the *raw* body bytes, before any JSON parsing.
        """
        if isinstance(raw_body, str):
            raw_body = raw_body.encode()
        expected = "sha256=" + hmac.new(signing_secret.encode(), raw_body, hashlib.sha256).hexdigest()
        return hmac.compare_digest(expected, signature_header or "")

    # ── internals ─────────────────────────────────────────────────────────
    def _request(self, method, path, body=None, headers=None, raw=False):
        url = self.base_url + path
        data = json.dumps(body).encode() if body is not None else None
        attempt = 0
        while True:
            req = urllib.request.Request(url, data=data, method=method)
            req.add_header("X-API-Key", self.api_key)
            req.add_header("User-Agent", f"bouncezero-python/{__version__}")
            if data is not None:
                req.add_header("Content-Type", "application/json")
            for k, v in (headers or {}).items():
                req.add_header(k, v)
            try:
                with urllib.request.urlopen(req, timeout=self.timeout) as resp:
                    payload = resp.read()
                    return payload if raw else json.loads(payload or b"{}")
            except urllib.error.HTTPError as e:
                status = e.code
                try:
                    payload = json.loads(e.read() or b"{}")
                except Exception:
                    payload = {}
                detail = payload.get("detail") or f"HTTP {status}"
                retry_after = e.headers.get("Retry-After")
                if (status == 429 or status >= 500) and attempt < self.max_retries:
                    attempt += 1
                    time.sleep(float(retry_after) if retry_after else min(2 ** attempt, 30))
                    continue
                if status in (401, 403):
                    raise AuthenticationError(detail, status, payload) from None
                if status == 402:
                    raise InsufficientCreditsError(detail, status, payload) from None
                if status == 404:
                    raise NotFoundError(detail, status, payload) from None
                if status == 429:
                    raise RateLimitError(
                        detail, status, payload,
                        retry_after=float(retry_after) if retry_after else None,
                    ) from None
                raise BounceZeroError(detail, status, payload) from None
            except urllib.error.URLError as e:
                if attempt < self.max_retries:
                    attempt += 1
                    time.sleep(min(2 ** attempt, 30))
                    continue
                raise BounceZeroError(f"Connection error: {e.reason}") from None
