#!/usr/bin/env python3
"""探测 v4: ahhz/ahtxq API 完整参数 + 返回 JSON, zixing 列表项"""
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: 先 goto 拿 cookie, 再 fetch grassrootsContentPageList
        print("="*60)
        print("[ahhz] grassrootsContentPageList API")
        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(3000)
            api = ("https://www.ahhz.gov.cn/huangshanzwgk/zwgk/site/label/8888?_=0.12345"
                   "&action=list&labelName=grassrootsContentPageList&siteId=6793339"
                   "&isDate=true&dateFormat=yyyy-MM-dd&length=50&organId=6615882&catId=1000260"
                   "&pageSize=15&pageIndex=1&type=4&keyWords=&isSetValue=true&isJson=true&result=")
            rr = await page.evaluate(f"fetch('{api}').then(r=>r.text()).catch(e=>'ERR:'+e.message)")
            print(f"  resp: {str(rr)[:600]}")
        except Exception as e:
            print(f"  ERROR: {e}")

        await page.wait_for_timeout(1500)

        # 2. ahtxq: publicInfoList API (与 ahshx 同款)
        print("="*60)
        print("[ahtxq] publicInfoList API")
        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(3000)
            api = ("https://www.ahtxq.gov.cn/huangshanzwgk/zwgk/site/label/8888?_=0.6789"
                   "&labelName=publicInfoList&siteId=6793339&organId=6615872&pageSize=15&pageIndex=1"
                   "&isDate=true&dateFormat=yyyy-MM-dd&length=50&type=4&action=list&result="
                   "&isJson=true&keyWords=&isSetValue=true&catIds=&catId=6717913")
            rr = await page.evaluate(f"fetch('{api}').then(r=>r.text()).catch(e=>'ERR:'+e.message)")
            print(f"  resp: {str(rr)[:600]}")
        except Exception as e:
            print(f"  ERROR: {e}")

        await page.wait_for_timeout(1500)

        # 3. zixing: 列表项提取 (标题+日期)
        print("="*60)
        print("[zixing] 列表项提取")
        try:
            await page.goto("http://www.zixing.gov.cn/zwgk/ztbd/zwgkgzydzl/zlhms/hjbf/hjzl/default.htm", timeout=45000, wait_until='domcontentloaded')
            await page.wait_for_timeout(2500)
            # 列表通常是 ul>li>a + span 日期
            items = await page.evaluate("""() => {
                const out = [];
                document.querySelectorAll('ul li, .list li, li').forEach(li => {
                    const a = li.querySelector('a');
                    if (a && /content_\\d+/.test(a.href)) {
                        out.push({t: a.innerText.trim().slice(0,60), h: a.href, li_html: li.outerHTML.slice(0,300)});
                    }
                });
                return out.slice(0,5);
            }""")
            for it in items:
                print(f"    item: [{it['t']}]")
                print(f"      html: {it['li_html'][:250]}")
        except Exception as e:
            print(f"  ERROR: {e}")

        await browser.close()

asyncio.run(main())
