"""Vérification côté serveur du captcha Cloudflare Turnstile."""

import json
import logging
from urllib.error import URLError
from urllib.parse import urlencode
from urllib.request import urlopen

from django.conf import settings

VERIFY_URL = "https://challenges.cloudflare.com/turnstile/v0/siteverify"
logger = logging.getLogger(__name__)


def captcha_enabled() -> bool:
    return bool(settings.TURNSTILE_SECRET_KEY)


def verify_captcha(token: str, ip: str | None = None) -> bool:
    """True si le jeton est valide. Sans clé secrète configurée, la vérification est désactivée."""
    if not captcha_enabled():
        return True
    if not token:
        return False
    payload = {"secret": settings.TURNSTILE_SECRET_KEY, "response": token}
    if ip:
        payload["remoteip"] = ip
    try:
        with urlopen(VERIFY_URL, data=urlencode(payload).encode(), timeout=5) as response:  # noqa: S310
            return bool(json.load(response).get("success"))
    except (URLError, TimeoutError, ValueError):
        logger.exception("Vérification Turnstile impossible")
        return False
