#!/usr/bin/env python3
"""探测 hanchuan: JS挑战过盾 + 列表结构"""
import asyncio, json, re, sys

UA = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.0.0 Safari/537.36"

async def main():
    from playwright.async_api import async_playwright
    from playwright_stealth import Stealth
    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']
        )
        stealth = Stealth()
        ctx = await browser.new_context(user_agent=UA, locale='zh-CN',
                                        viewport={'width': 1440, 'height': 900}, timezone_id='Asia/Shanghai')
        await stealth.apply_stealth_async(ctx)
        page = await ctx.new_page()

        url = "http://www.hanchuan.gov.cn/tzgg/index.jhtml"
        print(f"[hanchuan] {url}")
        try:
            r = await page.goto(url, wait_until='domcontentloaded', timeout=45000)
            await page.wait_for_timeout(8000)
            html = await page.content()
            t = await page.title()
            print(f"  status={r.status if r else '?'} title={t[:60]} len={len(html)}")
            # 是否还是挑战页
            if 'JbU' in html[:3000] or len(html) < 5000:
                print("  [WAF] 可能仍是挑战页, 等待更久")
                await page.wait_for_timeout(8000)
                html = await page.content()
                t = await page.title()
                print(f"  再等: title={t[:60]} len={len(html)}")
            # 列表项
            items = await page.evaluate("""() => {
                const out = [];
                document.querySelectorAll('li a, .list a, ul a').forEach(a => {
                    const t = (a.innerText||'').trim();
                    if (t && t.length > 8) out.push({t: t.slice(0,50), h: a.href});
                });
                return out.slice(0,10);
            }""")
            for it in items:
                print(f"  item: [{it['t']}] {it['h'][:90]}")
            # 分页
            pager = await page.evaluate("""() => {
                const out = [];
                document.querySelectorAll('a').forEach(a => {
                    const t = (a.innerText||'').trim();
                    if (/^(下一页|末页|首页|上一页|\\d+)$/.test(t)) out.push({t, h: a.href});
                });
                return out.slice(0,15);
            }""")
            for pg in pager:
                print(f"  pager: [{pg['t']}] {pg['h'][:90]}")
            tots = await page.evaluate("document.body.innerText.match(/共\\s*\\d+\\s*条|\\d+\\s*条/g)")
            print(f"  total: {tots[:3] if tots else 'None'}")
        except Exception as e:
            print(f"  ERR: {str(e)[:100]}")

        await browser.close()

asyncio.run(main())
