#!/usr/bin/env python3
"""
crawl_hngy_tzgg.py - 桂阳县-通知公告 (www.hngy.gov.cn)
站点: 湖南郴州桂阳县 (MMB1 防护, 与 zixing 同款; Server: core, MM_ cookie)
过盾: playwright-stealth, goto 后 DOM 即真实页面
列表: 纯静态分页 default.htm + default_N.htm, total=9512 条 (475页), 每页 20 条
  列表项: <li><span>YYYY-MM-DD</span><a href="content_XXXX.html" title="标题">标题</a></li>
详情: content_XXXX.html, meta ArticleTitle/PubDate/ContentSource, 正文 div.xl-content (截断 div.xl-weixin 二维码)
"""
import sys, os, re, asyncio, fcntl, time
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from crawler_lib import push_to_searchdb

BASE = "https://www.hngy.gov.cn"
LIST_DIR = "/zwgk/zwdt/tzgg"
LOCK_FILE = "/tmp/hngy_tzgg.lock"
SITE_NAME = "桂阳县-通知公告"

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

def acquire_lock(max_wait=1800):
    fd = open(LOCK_FILE, 'w')
    try:
        fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
        return fd
    except BlockingIOError:
        print(f"  [LOCK] 另一 hngy 实例运行中, 等待释放 (最多 {max_wait}s)...")
        deadline = time.time() + max_wait
        while time.time() < deadline:
            try:
                fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
                return fd
            except BlockingIOError:
                time.sleep(10)
        print("  [LOCK] 等待超时, 放弃")
        return None


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()

        # 过盾: 列表第一页
        first_url = BASE + LIST_DIR + "/default.htm"
        try:
            resp = await page.goto(first_url, wait_until='domcontentloaded', timeout=35000)
            await page.wait_for_timeout(6000)
            html = await page.content()
            m = re.search(r'<title>([^<]*)</title>', html)
            print(f"  [LOAD] status={resp.status if resp else '?'} title={m.group(1) if m else '?'} len={len(html)}")
            if m and ('NWAF' in m.group(1) or 'Environment Checking' 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

        # 抓列表 (span 在前, a 在后)
        items_all = []
        seen = set()
        for pg in range(1, pages + 1):
            if pg == 1:
                url = first_url
            else:
                url = BASE + LIST_DIR + f"/default_{pg-1}.htm"
            try:
                resp = await page.goto(url, wait_until='domcontentloaded', timeout=30000)
                await page.wait_for_timeout(2500)
                html = await page.content()
            except Exception as e:
                print(f"  [LIST ERR p{pg}] {str(e)[:100]}")
                break
            items = await page.evaluate("""() => {
                const out = [];
                document.querySelectorAll('li').forEach(li => {
                    const a = li.querySelector('a[href*="content_"]');
                    if (a) {
                        const sp = li.querySelector('span');
                        out.push({t: a.innerText.trim(), h: a.href, d: sp ? sp.innerText.trim() : ''});
                    }
                });
                return out;
            }""")
            if not items:
                print(f"  [p{pg}] 无列表项, 停止")
                break
            new_rows = 0
            for it in items:
                if it['h'] and it['h'] not in seen:
                    seen.add(it['h'])
                    items_all.append({'url': it['h'], 'title': it['t'], 'date': it['d']})
                    new_rows += 1
            print(f"  第{pg}页: {len(items)} 条, 新增 {new_rows} (累计 {len(items_all)})")
            has_next = await page.evaluate(f"() => document.querySelectorAll('a[href*=\"default_{pg}.htm\"]').length > 0")
            if not has_next:
                print(f"  [p{pg}] 无下一页")
                break

        print(f"  [LIST] 去重后 {len(items_all)} 条")

        # 详情页
        records = []
        for idx, it in enumerate(items_all):
            print(f"  [{idx+1}/{len(items_all)}] {it['title'][:40]}...")
            try:
                resp = await page.goto(it['url'], wait_until='domcontentloaded', timeout=30000)
                await page.wait_for_timeout(2500)
                html = await page.content()
            except Exception as e:
                print(f"    [DETAIL ERR] {str(e)[:100]}")
                continue
            title = it['title']
            m = re.search(r'<meta\s+name="ArticleTitle"\s+content="([^"]*)"', html)
            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="([^"]*)"', html)
            if m:
                dm = re.search(r'\d{4}-\d{2}-\d{2}', m.group(1))
                if dm:
                    pub_date = dm.group()
            # 正文 div.xl-content (截断到 xl-weixin 二维码)
            content = ""
            m = re.search(r'class="xl-content[^"]*"[^>]*>([\s\S]*?)</div>\s*<div[^>]*class="[^"]*xl-weixin', html)
            if m:
                content = m.group(1).strip()
            if not content:
                m = re.search(r'class="xl-content[^"]*"[^>]*>([\s\S]*?)</div>', html)
                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": "",
            })
        await browser.close()

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


def main():
    import argparse
    parser = argparse.ArgumentParser()
    parser.add_argument("--pages", type=int, default=5)
    args = parser.parse_args()
    lock = acquire_lock()
    if not lock:
        return
    try:
        n = asyncio.run(run_async(pages=args.pages))
        print(f"Done: {n} records")
    finally:
        os.close(lock.fileno())


if __name__ == "__main__":
    main()
