# Imports
from os import getenv as env
import requests, logging


# Create logger
log = logging.getLogger(__name__)


# Function to verify CAPTCHA response
def verify_captcha(token: str) -> bool:
    """
    Verify the CAP response token with the CAP server.
    
    Args:
        token (str): The CAP response token to verify.

    Returns:
        bool: True if the token is valid, False otherwise.
    """
    if not token:
        return False

    try:
        response = requests.post(
            f"https://cap.alfieking.dev/{env('CAP_KEY', default='')}/siteverify",
            json={
                'secret': env('CAP_SECRET', default=''),
                'response': token,
            },
            timeout=10
        )

        response.raise_for_status()
        if response.status_code != 200:
            log.error("CAPTCHA verification failed with status code: %s", response.status_code)
            return False
        return response.json().get('success', False)
    
    except Exception as e:
        log.error("Error verifying CAPTCHA: %s", e)
        return False