import secrets
from typing import Any

from fastapi import HTTPException

SAFE_METHODS = {"GET", "HEAD", "OPTIONS"}


def generate_csrf_token() -> str:
    return secrets.token_urlsafe(32)


def validate_csrf(request: Any, cookie_name: str) -> None:
    if request.method in SAFE_METHODS:
        return
    auth_header = request.headers.get("Authorization", "")
    if auth_header.lower().startswith("bearer "):
        return

    cookie_token = request.cookies.get(cookie_name)
    header_token = request.headers.get("X-CSRF-Token")

    if not cookie_token or not header_token:
        raise HTTPException(403, "Missing CSRF token")
    if not secrets.compare_digest(cookie_token, header_token):
        raise HTTPException(403, "CSRF token mismatch")
