"""POST /v1/paddle/webhook — Paddle billing webhook receiver.

Signature-verified, idempotent. Always returns 200 to prevent Paddle
retries on application-level errors (logged, not surfaced).
"""

from __future__ import annotations

import json
import logging

from fastapi import APIRouter, Request
from fastapi.responses import JSONResponse

_log = logging.getLogger(__name__)

router = APIRouter()


async def _get_webhook_secret() -> str:
    """Retrieve Paddle webhook secret from Secret Manager."""
    from google.cloud import secretmanager

    client = secretmanager.SecretManagerServiceClient()
    name = "projects/complyform-prod/secrets/paddle-webhook-secret/versions/latest"
    response = client.access_secret_version(request={"name": name})
    return response.payload.data.decode("utf-8")


@router.post("/v1/paddle/webhook")
async def paddle_webhook(request: Request) -> JSONResponse:
    """Paddle billing webhook endpoint.

    Not rate-limited by Cloud Armor — Paddle's retry infrastructure
    requires reliable delivery. Signature verification prevents abuse.
    """
    from backend.billing.webhook_handler import (
        handle_webhook_event,
        verify_paddle_signature,
    )

    raw_body = await request.body()
    signature = request.headers.get("Paddle-Signature", "")

    if not signature:
        _log.warning("Paddle webhook: missing signature header")
        return JSONResponse({"error": "missing_signature"}, status_code=401)

    try:
        secret = await _get_webhook_secret()
    except Exception:
        _log.exception("Failed to retrieve Paddle webhook secret")
        return JSONResponse({"status": "ok"})

    if not verify_paddle_signature(raw_body, signature, secret):
        _log.warning("Paddle webhook: signature verification failed")
        return JSONResponse({"error": "invalid_signature"}, status_code=401)

    try:
        event = json.loads(raw_body)
    except json.JSONDecodeError:
        _log.warning("Paddle webhook: invalid JSON body")
        return JSONResponse({"status": "ok"})

    try:
        await handle_webhook_event(event)
    except Exception:
        _log.exception(
            "Paddle webhook handler error for event %s", event.get("event_id", "?")
        )

    return JSONResponse({"status": "ok"})
