#!/usr/bin/env python3
"""
AWS WAF 挑战求解器 — 用 headless Chromium 访问 DeepSeek，
自动通过 JS 挑战，提取 aws-waf-token cookie。
"""
import asyncio
import json
import sys
from playwright.async_api import async_playwright

TARGET = "https://chat.deepseek.com/"
OUTPUT = "/tmp/waf_token.json"


async def solve() -> dict:
    async with async_playwright() as p:
        browser = await p.chromium.launch(
            headless=True,
            args=[
                "--no-sandbox",
                "--disable-gpu",
                "--disable-dev-shm-usage",
                "--disable-setuid-sandbox",
                "--no-first-run",
                "--no-zygote",
                "--single-process",
            ],
        )
        context = await browser.new_context(
            user_agent="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36",
            viewport={"width": 1920, "height": 1080},
        )
        page = await context.new_page()

        try:
            # 访问 DeepSeek，等待 WAF 挑战自动完成
            await page.goto(TARGET, wait_until="domcontentloaded", timeout=30000)
            # 等待页面完全加载（WAF 挑战通过后会自动刷新）
            await page.wait_for_load_state("networkidle", timeout=30000)
            await asyncio.sleep(3)

            # 提取所有 cookie
            cookies = await context.cookies()
            result = {
                "cookies": {c["name"]: c["value"] for c in cookies},
                "all": cookies,
            }

            # 找 aws-waf-token
            waf_token = None
            for c in cookies:
                if "aws-waf" in c["name"].lower() or "waf" in c["name"].lower():
                    waf_token = c["value"]
                    print(f"[OK] WAF cookie: {c['name']}={c['value'][:40]}...")
                print(f"  cookie: {c['name']} (domain={c.get('domain','')})")

            if waf_token:
                result["waf_token"] = waf_token
                print(f"[OK] WAF token obtained successfully")
            else:
                print("[WARN] No WAF cookie found, listing all cookies:")
                for c in cookies:
                    print(f"  {c['name']}: {c['value'][:50]}...")

        except Exception as e:
            print(f"[ERR] {e}")
            result = {"error": str(e)}
        finally:
            await browser.close()

    return result


if __name__ == "__main__":
    result = asyncio.run(solve())
    with open(OUTPUT, "w") as f:
        json.dump(result, f, indent=2)
    print(f"[OK] Saved to {OUTPUT}")
    if result.get("waf_token"):
        print(f"WAF_TOKEN={result['waf_token']}")
    else:
        sys.exit(1)