#!/usr/bin/env python3
"""探测 ahtxq: tzgg 分页方式 + 列表结构"""
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, viewport={'width':1366,'height':900})
        await stealth.apply_stealth_async(ctx)
        page = await ctx.new_page()

        print("="*60)
        print("[ahtxq] tzgg 列表结构")
        await page.goto("https://www.ahtxq.gov.cn/zxzx/tzgg/index.html", timeout=30000, wait_until='domcontentloaded')
        await page.wait_for_timeout(3500)
        # 列表容器结构
        lst = await page.evaluate("""() => {
            const out = [];
            document.querySelectorAll('ul li').forEach(li => {
                const a = li.querySelector('a');
                if (a && /\\d{6,}\\.html/.test(a.href)) {
                    out.push({t: (a.innerText||'').trim().slice(0,50), h: a.href, lihtml: li.outerHTML.slice(0,250)});
                }
            });
            return out.slice(0,3);
        }""")
        for it in lst:
            print(f"  item: [{it['t']}]")
            print(f"    {it['lihtml']}")
        # 分页链接
        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'][:100]}")
        # total
        tot = await page.evaluate("document.body.innerText.match(/共\\s*\\d+\\s*条|\\d+\\s*条/g)")
        print(f"  total: {tot[:3] if tot else 'None'}")

        await browser.close()

asyncio.run(main())
