"""Webhook utilities for verifying Kawaa webhook signatures."""

import hashlib
import hmac
from dataclasses import dataclass
from typing import Any, Dict, Optional

from .exceptions import ValidationError
from .models import JobStatus


@dataclass
class WebhookEvent:
    """Parsed webhook event."""

    event: str
    job_id: str
    status: JobStatus
    created_at: Optional[str]
    completed_at: Optional[str]
    total: int
    valid: int
    invalid: int
    risky: int
    unknown: int
    download_url: str
    raw_payload: Dict[str, Any]

    @classmethod
    def from_dict(cls, data: Dict[str, Any]) -> "WebhookEvent":
        """Create from webhook payload."""
        results = data.get("results", {})
        return cls(
            event=data.get("event", ""),
            job_id=data.get("job_id", ""),
            status=JobStatus(data.get("status", "completed")),
            created_at=data.get("created_at"),
            completed_at=data.get("completed_at"),
            total=results.get("total", 0),
            valid=results.get("valid", 0),
            invalid=results.get("invalid", 0),
            risky=results.get("risky", 0),
            unknown=results.get("unknown", 0),
            download_url=data.get("download_url", ""),
            raw_payload=data,
        )


def verify_signature(
    payload: bytes,
    signature: str,
    secret: str,
) -> bool:
    """
    Verify the HMAC signature of a webhook payload.

    Args:
        payload: Raw request body as bytes.
        signature: Value of X-Kawaa-Signature header.
        secret: Your webhook secret.

    Returns:
        True if signature is valid, False otherwise.

    Example:
        >>> from kawaa.webhooks import verify_signature
        >>> is_valid = verify_signature(
        ...     payload=request.body,
        ...     signature=request.headers["X-Kawaa-Signature"],
        ...     secret="your-webhook-secret"
        ... )
    """
    if not signature or not secret:
        return False

    # Signature format: "sha256=<hex>"
    if signature.startswith("sha256="):
        signature = signature[7:]

    expected = hmac.new(
        secret.encode("utf-8"),
        payload,
        hashlib.sha256,
    ).hexdigest()

    return hmac.compare_digest(expected, signature)


def parse_webhook(
    payload: bytes,
    signature: Optional[str] = None,
    secret: Optional[str] = None,
) -> WebhookEvent:
    """
    Parse and optionally verify a webhook payload.

    Args:
        payload: Raw request body as bytes.
        signature: Value of X-Kawaa-Signature header (optional).
        secret: Your webhook secret (required if signature provided).

    Returns:
        WebhookEvent with parsed data.

    Raises:
        ValidationError: If signature verification fails.

    Example:
        >>> from kawaa.webhooks import parse_webhook
        >>>
        >>> # In your webhook handler:
        >>> event = parse_webhook(
        ...     payload=request.body,
        ...     signature=request.headers.get("X-Kawaa-Signature"),
        ...     secret="your-webhook-secret"
        ... )
        >>> print(f"Job {event.job_id} completed: {event.valid} valid emails")
    """
    import json

    # Verify signature if provided
    if signature and secret:
        if not verify_signature(payload, signature, secret):
            raise ValidationError("Invalid webhook signature")

    # Parse JSON payload
    try:
        data = json.loads(payload)
    except json.JSONDecodeError as e:
        raise ValidationError(f"Invalid JSON payload: {e}")

    return WebhookEvent.from_dict(data)


# Flask integration helper
def flask_webhook_handler(secret: str):
    """
    Decorator for Flask webhook handlers.

    Args:
        secret: Your webhook secret for signature verification.

    Returns:
        Decorator function.

    Example:
        >>> from flask import Flask
        >>> from kawaa.webhooks import flask_webhook_handler
        >>>
        >>> app = Flask(__name__)
        >>>
        >>> @app.route("/webhook", methods=["POST"])
        >>> @flask_webhook_handler("your-webhook-secret")
        >>> def handle_webhook(event):
        ...     print(f"Job {event.job_id} completed!")
        ...     return "", 200
    """
    from functools import wraps

    def decorator(f):
        @wraps(f)
        def wrapper(*args, **kwargs):
            from flask import request, abort

            signature = request.headers.get("X-Kawaa-Signature")
            try:
                event = parse_webhook(request.data, signature, secret)
            except ValidationError:
                abort(401)

            return f(event, *args, **kwargs)

        return wrapper

    return decorator


# FastAPI integration helper
def fastapi_webhook_handler(secret: str):
    """
    Dependency for FastAPI webhook handlers.

    Args:
        secret: Your webhook secret for signature verification.

    Returns:
        Dependency function.

    Example:
        >>> from fastapi import FastAPI, Request, Depends
        >>> from kawaa.webhooks import fastapi_webhook_handler
        >>>
        >>> app = FastAPI()
        >>> get_webhook_event = fastapi_webhook_handler("your-webhook-secret")
        >>>
        >>> @app.post("/webhook")
        >>> async def handle_webhook(event: WebhookEvent = Depends(get_webhook_event)):
        ...     print(f"Job {event.job_id} completed!")
        ...     return {"status": "ok"}
    """
    async def dependency(request):
        from fastapi import HTTPException

        signature = request.headers.get("X-Kawaa-Signature")
        body = await request.body()

        try:
            return parse_webhook(body, signature, secret)
        except ValidationError:
            raise HTTPException(status_code=401, detail="Invalid signature")

    return dependency
