#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""服务器 playwright 过盾测试 — 蒲江瑞数 + wenshang JS渲染"""
import re, sys, time
from playwright.sync_api import sync_playwright

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

TESTS = [
    ("蒲江瑞数", "http://www.pujiang.gov.cn/pjxrmzf/c160163/nav_list.shtml", {"www.pujiang.gov.cn": "171.221.172.137", "pujiang.gov.cn": "171.221.172.137"}),
    ("wenshang", "http://www.wenshang.gov.cn/col/col61746/index.html?vc_xxgkarea=1137083000433565XHA&number=A0002001&jh=263", {"www.wenshang.gov.cn": "27.221.53.71", "wenshang.gov.cn": "27.221.53.71"}),
]

with sync_playwright() as p:
    for name, url, maps in TESTS:
        print(f"\n=== {name} ===", flush=True)
        rules = ", ".join(f"MAP {k} {v}" for k, v in maps.items())
        try:
            browser = p.chromium.launch(headless=True,
                                        args=["--disable-blink-features=AutomationControlled", "--no-sandbox", f"--host-resolver-rules={rules}"])
        except Exception as e:
            print(f"[X] 浏览器启动失败: {e}", flush=True)
            continue
        try:
            ctx = browser.new_context(user_agent=UA, locale="zh-CN", viewport={"width": 1920, "height": 1080})
            page = ctx.new_page()
            try:
                page.goto(url, timeout=30000, wait_until="domcontentloaded")
            except Exception as e:
                print(f"  goto: {type(e).__name__}", flush=True)
            html = ""
            for i in range(12):
                time.sleep(2)
                try:
                    html = page.content()
                except Exception:
                    continue
                if "_ts" not in html and len(html) > 5000:
                    break
            print(f"  页面 {len(html)} bytes, 瑞数残留: {'_ts' in html}", flush=True)
            title = re.findall(r"<title>(.*?)</title>", html)
            print(f"  title: {title[:1]}", flush=True)
            links = re.findall(r'href="([^"]*(?:content_|art_)[^"]*)"', html)
            print(f"  详情链接数: {len(links)}, 样本: {links[:2]}", flush=True)
        except Exception as e:
            print(f"[X] 测试异常: {e}", flush=True)
        finally:
            browser.close()
