"""IDReady server-side Python SDK, version 0.1.0 (Python 3.10+, standard library).

Keep API keys in your server's secret manager. No automatic retries are performed.
Use the same idempotency key when retrying a creation request.
"""
import hashlib
import hmac
import json
import time
from urllib.error import HTTPError, URLError
from urllib.parse import urlencode, urlsplit
from urllib.request import Request, urlopen

__version__ = "0.1.0"


class IDReadyError(Exception):
    def __init__(self, status, message):
        self.status = status
        super().__init__(f"IDReady HTTP {status}: {message}")


class IDReady:
    def __init__(self, api_key, base_url="https://app.realidchecker.com/api/v2"):
        if not isinstance(api_key, str) or not api_key.startswith(("idr_test_", "idr_live_")):
            raise ValueError("A server-side test or live IDReady key is required")
        parsed = urlsplit(base_url)
        if parsed.scheme != "https" or parsed.username or parsed.password or parsed.query or parsed.fragment:
            raise ValueError("Use an HTTPS API base URL without credentials, query or fragment")
        self._key, self._base = api_key, base_url.rstrip("/")

    def _request(self, method, path, body=None, idempotency_key=None):
        headers = {"Authorization": "Bearer " + self._key, "Accept": "application/json"}
        if idempotency_key:
            headers["Idempotency-Key"] = idempotency_key
        raw = json.dumps(body).encode() if body is not None else None
        if raw:
            headers["Content-Type"] = "application/json"
        request = Request(self._base + path, data=raw, headers=headers, method=method)
        # urllib normally follows redirects, potentially forwarding auth. Disable them.
        from urllib.request import HTTPRedirectHandler, build_opener

        class NoRedirect(HTTPRedirectHandler):
            def redirect_request(self, req, fp, code, msg, hdrs, newurl):
                return None

        try:
            with build_opener(NoRedirect).open(request, timeout=30) as response:
                return json.loads(response.read())
        except HTTPError as exc:
            # Do not include arbitrary upstream bodies or credentials in exceptions.
            raise IDReadyError(exc.code, "Request failed; inspect the status and API documentation") from None
        except (URLError, TimeoutError) as exc:
            raise IDReadyError(0, "Connection failed; retry with the same idempotency key") from None

    def create_verification(self, details, *, idempotency_key):
        return self._request("POST", "/verifications", details, idempotency_key)

    def get_verification(self, verification_id):
        return self._request("GET", f"/verifications/{int(verification_id)}")

    def list_verifications(self, *, before=None, limit=50):
        query = {"limit": int(limit)}
        if before is not None:
            query["before"] = int(before)
        return self._request("GET", "/verifications?" + urlencode(query))


def verify_webhook(secret, raw_body, timestamp, signature, *, tolerance=300):
    """Verify original bytes and timestamp BEFORE parsing JSON. Then deduplicate events."""
    try:
        if not isinstance(raw_body, bytes) or not secret or abs(time.time() - int(timestamp)) > tolerance:
            return False
        expected = hmac.new(secret.encode(), str(timestamp).encode() + b"." + raw_body, hashlib.sha256).hexdigest()
        return hmac.compare_digest(expected, signature)
    except (ValueError, TypeError):
        return False
