#!/usr/bin/env python3
"""探测 gddrc: API 返回 (带重试)"""
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()

        ok = False
        for attempt in range(3):
            try:
                r = await page.goto("https://drc.gd.gov.cn/gdsnyj/gkmlpt/index#3869", wait_until='domcontentloaded', timeout=60000)
                await page.wait_for_timeout(10000)
                t = await page.title()
                print(f"[try{attempt+1}] {r.status if r else '?'} {t[:50]}")
                ok = True
                break
            except Exception as e:
                print(f"[try{attempt+1}] ERR {str(e)[:60]}")
                await page.wait_for_timeout(20000)

        if ok:
            api = "https://drc.gd.gov.cn/gdsnyj/gkmlpt/api/all/3869?page=1&sid=257"
            rr = await page.evaluate(f"fetch('{api}').then(r=>r.text()).catch(e=>'ERR:'+e.message)")
            print(f"\nAPI resp ({len(str(rr))} chars):")
            print(str(rr)[:2000])

        await browser.close()

asyncio.run(main())
