#!/usr/bin/env python3
"""探测 v6: ahhz 渲染后真实 href + ahtxq 栏目树"""
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()

        # 1. ahhz: 渲染后真实 href
        print("="*60)
        print("[ahhz] 渲染后真实链接")
        try:
            await page.goto("https://www.ahhz.gov.cn/zwgk/grassroots/column/6615882?&catId=1000260", timeout=45000, wait_until='domcontentloaded')
            await page.wait_for_timeout(5000)
            links = await page.evaluate("""() => {
                const out = [];
                document.querySelectorAll('a').forEach(a => {
                    const t = (a.innerText||'').trim();
                    if (t && (t.includes('批复') || t.includes('公示') || t.includes('报告') || t.includes('许可') || /20\\d{2}/.test(t)) && a.href.includes('ahhz')) {
                        out.push({t: t.slice(0,50), h: a.href, cls: a.className.slice(0,30), parent: a.parentElement ? a.parentElement.tagName : ''});
                    }
                });
                return out.slice(0,12);
            }""")
            for l in links:
                print(f"  [{l['t']}] cls={l['cls']} par={l['parent']}\n    {l['h'][:130]}")
            if not links:
                # 找列表容器
                html = await page.content()
                m = re.findall(r'href="([^"]*content[^"]*)"', html)
                print(f"  无链接匹配, content hrefs: {list(dict.fromkeys(m))[:8]}")
        except Exception as e:
            print(f"  ERROR: {e}")

        await page.wait_for_timeout(1500)

        # 2. ahtxq: 栏目树
        print("="*60)
        print("[ahtxq] 栏目树")
        try:
            await page.goto("https://www.ahtxq.gov.cn/zwgk/public/column/6615872?type=2&nav=0", timeout=45000, wait_until='domcontentloaded')
            await page.wait_for_timeout(5000)
            links = await page.evaluate("""() => {
                const out = [];
                document.querySelectorAll('a').forEach(a => {
                    const t = (a.innerText||'').trim();
                    const h = a.href;
                    if (t && h.includes('column/') && t.length < 25) out.push({t, h});
                });
                return out;
            }""")
            # 去重
            seen = set()
            for l in links:
                if l['h'] not in seen:
                    seen.add(l['h'])
                    print(f"  col: [{l['t']}] {l['h'][:110]}")
                if len(seen) > 25: break
        except Exception as e:
            print(f"  ERROR: {e}")

        await browser.close()

asyncio.run(main())
