#!/usr/bin/env python3
"""ahshx WAF 冷却探测 - playwright 版
每 10min 用 playwright 探测列表页; 解封(非NWAF页)则运行 crawl_ahshx_hpgs.py
"""
import subprocess, time, sys, datetime, asyncio, re

LIST_URL = "https://www.ahshx.gov.cn/zwgk/public/column/6616370?type=4&catId=6727117&action=list&nav=3"
MAX_ATTEMPTS = 30  # 30 * 10min = 5h

STEALTH = """
Object.defineProperty(navigator, 'webdriver', {get: () => undefined});
window.chrome = { runtime: {}, loadTimes: function(){}, csi: function(){}, app: {} };
Object.defineProperty(navigator, 'plugins', {get: () => {
  const arr = [{name: 'Chrome PDF Plugin'},{name: 'Chrome PDF Viewer'},{name: 'Native Client'}];
  arr.item = (i) => arr[i]; arr.namedItem = (n) => arr.find(x => x.name === n);
  arr.refresh = () => {}; return arr;
}});
Object.defineProperty(navigator, 'languages', {get: () => ['zh-CN', 'zh', 'en-US']});
Object.defineProperty(navigator, 'platform', {get: () => 'Win32'});
"""


async def probe_once():
    from playwright.async_api import async_playwright
    async with async_playwright() as p:
        browser = await p.chromium.launch(
            headless=True,
            executable_path='/root/.cache/ms-playwright/chromium-1228/chrome-linux64/chrome',
            args=['--no-sandbox', '--disable-setuid-sandbox', '--disable-blink-features=AutomationControlled']
        )
        ctx = await browser.new_context(
            user_agent='Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 Chrome/125.0.0.0 Safari/537.36',
            locale='zh-CN',
        )
        await ctx.add_init_script(STEALTH)
        page = await ctx.new_page()
        try:
            resp = await page.goto(LIST_URL, wait_until='domcontentloaded', timeout=25000)
            await page.wait_for_timeout(8000)
            html = await page.content()
            m = re.search(r'<title>([^<]*)</title>', html)
            title = m.group(1) if m else '?'
            ok = ('NWAF' not in title) and ('Environment' not in title) and (len(html) > 5000)
            print(f"  status={resp.status if resp else '?'} title={title} len={len(html)} ok={ok}")
            return ok, html
        except Exception as e:
            print(f"  ERR: {str(e)[:100]}")
            return False, ""
        finally:
            await browser.close()


for i in range(1, MAX_ATTEMPTS + 1):
    now = datetime.datetime.now().strftime("%m-%d %H:%M:%S")
    ok, html = asyncio.run(probe_once())
    if ok:
        print(f"[{now}] ✅ 解封! 运行爬虫...")
        r = subprocess.run(["python3", "/root/gov_crawler/crawl_ahshx_hpgs.py", "--pages", "1"],
                          capture_output=True, text=True, timeout=300)
        print("STDOUT:", r.stdout[-2500:])
        print("STDERR:", r.stderr[-500:])
        sys.exit(0)
    print(f"[{now}] 尝试 {i}/{MAX_ATTEMPTS}: 仍被 WAF 拦截, 10min 后重试")
    time.sleep(600)

print("超过 5h 仍未解封, 退出")
sys.exit(1)
