from fastapi import Header, HTTPException
import httpx
import os

SECRET_KEY = "0x4AAAAAAC1FejGhoIl8dbeIh8wB5WBhkB0"
print("Check SECRET_KEY đã nhận chưa:", SECRET_KEY)

async def verify_turnstile(x_turnstile_token: str = Header(None)):
    if os.getenv("APP_ENV", "production") == "development":
        return

    if not SECRET_KEY:
        raise HTTPException(status_code=500, detail="Lỗi server: Chưa cấu hình TURNSTILE_SECRET_KEY")

    if not x_turnstile_token:
        raise HTTPException(status_code=403, detail="Vui lòng xác minh bạn không phải robot!")

    async with httpx.AsyncClient() as client:
        res = await client.post(
            "https://challenges.cloudflare.com/turnstile/v0/siteverify",
            data={"secret": SECRET_KEY, "response": x_turnstile_token}
        )
        data = res.json()

        if not data.get("success"):
            raise HTTPException(status_code=403, detail="Xác minh thất bại hoặc Token đã hết hạn!")