import httpx
from user_scanner.core.result import Result


async def _check(email: str) -> Result:
    url = "https://huggingface.co/api/check-user-email"
    show_url = "https://huggingface.co"
    payload = {'email': email}

    headers = {
        'User-Agent': "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/143.0.0.0 Safari/537.36",
        'Accept-Encoding': "identity",
        'referer': "https://huggingface.co/join",
    }

    async with httpx.AsyncClient(timeout=15.0, http2=True) as client:
        try:
            response = await client.post(url, json=payload, headers=headers, timeout=15.0)
            res_text = response.text
            st_code = response.status_code

            if st_code == 429:
                return Result.error("Rate limited wait for few minutes")

            if st_code == 200:
                if "already exists" in res_text:
                    return Result.taken(url=show_url)

                if "This email address is available." in res_text:
                    return Result.available(url=show_url)

            return Result.error(f"HTTP Error: {response.status_code}, report it via GitHub issues")

        except Exception as e:
            return Result.error(e)


async def validate_huggingface(email: str) -> Result:
    return await _check(email)
