#!/usr/bin/env python3
"""
crawl_cnqc_zdly.py - 青川县人民政府-重点领域信息公开 (cnqc.gov.cn)
站点: 四川广元青川县 (瑞数4代+帝联NWAF 双WAF, 与 ahshx/gdqy 同版本)
过盾: playwright-stealth, 全程 goto (fetch 被瑞数拒, goto 过盾后 ~7s/页)
列表: /New/List/20171128112728617.html?page=N (重点领域信息公开, 50页)
  ul > li > a[title]+span日期, 详情 /New/Detail/xxx.html
详情: meta ArticleTitle/PubDate/ContentSource, 正文 div.msg-content (截断到二维码 div_div 前)
限速: 详情间 3-8s 随机抖动 (用户要求)
注意: 用户原URL(20171201155541049.htmlz)已404, 用重点领域信息公开替代
"""
import sys, os, re, asyncio, random, time
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from crawler_lib import push_to_searchdb

BASE = "http://cnqc.gov.cn"
SITE_NAME = "青川县-重点领域信息公开"
LIST_ID = "20171128112728617"
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 run_async(pages=5):
    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']
        )
        ctx = await browser.new_context(user_agent=UA, locale='zh-CN',
                                        viewport={'width': 1440, 'height': 900}, timezone_id='Asia/Shanghai')
        stealth = Stealth()
        await stealth.apply_stealth_async(ctx)
        page = await ctx.new_page()

        # 过盾: 首页
        try:
            resp = await page.goto(BASE + '/', wait_until='domcontentloaded', timeout=45000)
            await page.wait_for_timeout(15000)
            html = await page.content()
            m = re.search(r'<title>([^<]*)</title>', html)
            print(f"  [LOAD] status={resp.status if resp else '?'} title={m.group(1)[:40] if m else '?'} len={len(html)}")
            if m and '请稍候' in m.group(1):
                print("  [WAF] 挑战未过")
                await browser.close()
                return 0
        except Exception as e:
            print(f"  [LOAD ERR] {str(e)[:120]}")
            await browser.close()
            return 0

        # 列表: goto ?page=N
        items_all = []
        seen = set()
        for pg in range(1, pages + 1):
            try:
                resp = await page.goto(f"{BASE}/New/List/{LIST_ID}.html?page={pg}", wait_until='domcontentloaded', timeout=40000)
                await page.wait_for_timeout(6000)
                html = await page.content()
            except Exception as e:
                print(f"  [LIST ERR p{pg}] {str(e)[:100]}")
                break
            rows = re.findall(r'<li>\s*<a href="([^"]*Detail[^"]*\.html)"[^>]*title="([^"]*)"[^>]*>[\s\S]{0,200}?</a>\s*<span>(\d{4}-\d{2}-\d{2})</span>', html)
            if not rows:
                rows = re.findall(r'<a href="([^"]*Detail[^"]*\.html)"[^>]*title="([^"]*)"[^>]*>[\s\S]{0,200}?</a>\s*<span>(\d{4}-\d{2}-\d{2})</span>', html)
            new_rows = 0
            for u, t, d in rows:
                url = u if u.startswith('http') else BASE + u
                if url not in seen:
                    seen.add(url)
                    items_all.append({"url": url, "title": t.strip(), "date": d})
                    new_rows += 1
            print(f"  第{pg}页: 解析 {len(rows)} 条, 新增 {new_rows} (累计 {len(items_all)})")
            if len(rows) < 15:
                print("  [END] 列表结束")
                break

        # 详情页 (goto + 3-8s 抖动)
        records = []
        for idx, it in enumerate(items_all):
            print(f"  [{idx+1}/{len(items_all)}] {it['title'][:36]}...")
            try:
                resp = await page.goto(it['url'], wait_until='domcontentloaded', timeout=40000)
                await page.wait_for_timeout(5000)
                dh = await page.content()
                if '请稍候' in dh[:2000]:
                    print("    [WAF] 详情被拦")
                    continue
            except Exception as e:
                print(f"    [DETAIL ERR] {str(e)[:100]}")
                continue
            # meta
            title = it['title']
            m = re.search(r'<meta\s+name="ArticleTitle"\s+content="([^"]*)"', dh)
            if m and m.group(1).strip():
                title = m.group(1).strip()
            pub_date = it['date']
            m = re.search(r'<meta\s+name="PubDate"\s+content="([^"]*)"', dh)
            if m:
                dm = re.search(r'\d{4}-\d{2}-\d{2}', m.group(1))
                if dm:
                    pub_date = dm.group()
            # 正文 msg-content (截断到二维码)
            content = ""
            m = re.search(r'<div class="msg-content">([\s\S]*?)</div>\s*<div id="div_div"', dh)
            if m:
                content = m.group(1).strip()
            if not content:
                m = re.search(r'<div class="msg-content">([\s\S]*?)</div>', dh)
                if m:
                    content = m.group(1).strip()
            if not content.strip():
                print("    [SKIP] 正文空")
                continue
            content = re.sub(r'href="/', 'href="' + BASE + '/', content)
            content = re.sub(r'src="/', 'src="' + BASE + '/', content)
            records.append({
                "title": title,
                "url": it['url'],
                "pub_date": pub_date,
                "site_name": SITE_NAME,
                "content": content,
                "summary": "",
            })
            if idx < len(items_all) - 1:
                await asyncio.sleep(random.uniform(3.0, 8.0))
        await browser.close()

    print(f"  共 {len(records)} 条有效")
    if records:
        push_to_searchdb(records, "cnqc_zdly")
    return len(records)


def main():
    import argparse
    parser = argparse.ArgumentParser()
    parser.add_argument("--pages", type=int, default=5)
    parser.add_argument("--all", action="store_true")
    args = parser.parse_args()
    pages = 50 if args.all else args.pages
    print(f"  {SITE_NAME} pages={pages}")
    cnt = asyncio.run(run_async(pages=pages))
    print(f"Done: {cnt} records")
    return 0


if __name__ == "__main__":
    sys.exit(main())
