import hashlib
import hmac
import json
import time


class WebhookVerifier:
    """Verify ZyndPay webhook signatures."""

    HEADER_NAME = "x-zyndpay-signature"

    def __init__(self, signing_secret: str):
        self._secret = signing_secret

    def verify(self, payload: str, signature: str, tolerance_seconds: int = 300) -> dict:
        """
        Verify a webhook signature and parse the event payload.

        Args:
            payload: The raw request body (string)
            signature: The value of the X-ZyndPay-Signature header
            tolerance_seconds: Max age of the event in seconds (default: 300)

        Returns:
            Parsed webhook event dict with "type", "data", etc.

        Raises:
            ValueError: If the signature is invalid or the event is too old.

        Example::

            verifier = zyndpay.webhooks
            event = verifier.verify(request.data, request.headers["X-ZyndPay-Signature"])
            print(event["type"])  # "payin.confirmed"
        """
        if not signature:
            raise ValueError("Missing webhook signature header")

        parts = signature.split(",")
        t_part = next((p for p in parts if p.startswith("t=")), None)
        v1_part = next((p for p in parts if p.startswith("v1=")), None)

        if not t_part or not v1_part:
            raise ValueError('Invalid webhook signature format — expected "t=<timestamp>,v1=<hmac>"')

        timestamp = int(t_part.replace("t=", ""))
        received_hmac = v1_part.replace("v1=", "")

        now = int(time.time())
        if abs(now - timestamp) > tolerance_seconds:
            raise ValueError(
                f"Webhook timestamp too old ({abs(now - timestamp)}s > {tolerance_seconds}s tolerance)"
            )

        signed_payload = f"{timestamp}.{payload}"
        expected_hmac = hmac.new(
            self._secret.encode("utf-8"),
            signed_payload.encode("utf-8"),
            hashlib.sha256,
        ).hexdigest()

        if not hmac.compare_digest(expected_hmac, received_hmac):
            raise ValueError("Webhook signature verification failed")

        return json.loads(payload)
