import httpx
import json
import urllib.parse
from user_scanner.core.result import Result


async def _check(email: str) -> Result:
    show_url = "https://hackthebox.com"
    register_url = "https://account.hackthebox.com/register"
    api_url = "https://account.hackthebox.com/api/v1/user/email/verify"

    headers = {
        'User-Agent': "Mozilla/5.0 (Linux; Android 10; K) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/145.0.0.0 Mobile Safari/537.36",
        'Accept': "application/json",
        'Accept-Encoding': "identity",
        'Content-Type': "application/json",
        'sec-ch-ua-platform': '"Android"',
        'sec-ch-ua': '"Not:A-Brand";v="99\", \"Google Chrome\";v=\"145\", \"Chromium\";v=\"145"',
        'sec-ch-ua-mobile': "?1",
        'x-requested-with': "XMLHttpRequest",
        'origin': "https://account.hackthebox.com",
        'sec-fetch-site': "same-origin",
        'sec-fetch-mode': "cors",
        'sec-fetch-dest': "empty",
        'referer': "https://account.hackthebox.com/register",
        'accept-language': "en-US,en;q=0.9",
        'priority': "u=1, i"
    }

    try:
        async with httpx.AsyncClient(timeout=15.0, follow_redirects=True) as client:
            r_init = await client.get(register_url, headers={'User-Agent': headers['User-Agent']})

            if r_init.status_code == 403:
                return Result.error("Caught by WAF or IP Block (403) during Handshake")

            xsrf_token_encoded = client.cookies.get("XSRF-TOKEN")
            if not xsrf_token_encoded:
                return Result.error("Failed to extract XSRF-TOKEN from HackTheBox")

            xsrf_token = urllib.parse.unquote(xsrf_token_encoded)
            headers['x-xsrf-token'] = xsrf_token

            payload = {"email": email}
            response = await client.post(api_url, content=json.dumps(payload), headers=headers)

            status = response.status_code

            if status == 403:
                return Result.error("Caught by WAF or IP Block (403) during Validation")

            if status == 422:
                resp_data = response.json()
                if "cannot use this email address" in str(resp_data):
                    return Result.taken(url=show_url)
                return Result.error(f"Validation error: {resp_data.get('message')}")

            if status in [200, 204]:
                return Result.available(url=show_url)

            if status == 429:
                return Result.error("Rate limited by HackTheBox")

            return Result.error(f"Unexpected status code: {status}")

    except httpx.ConnectTimeout:
        return Result.error("Connection timed out! maybe region blocks")
    except Exception as e:
        return Result.error(e)


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