#!/usr/bin/env python3
"""
crawl_ahhz_hpgs.py - 徽州区生态环境分局-建设项目环评审批 (www.ahhz.gov.cn)
站点: 帝联NWAF + 瑞数4代双WAF (与 ahshx/黄山 同款)
过盾: playwright + playwright-stealth
列表: GET /huangshanzwgk/zwgk/site/label/8888 labelName=grassrootsContentPageList
  siteId=6793339&organId=6615882&catId=1000260&pageSize=15&pageIndex=N
  &isDate=true&dateFormat=yyyy-MM-dd&length=50&type=4&action=list&isJson=true
  返回 JSON {data:[{title, contentId, publishDate, fileNum, author}], total, pageCount}
详情: /zwgk/grassroots/{organ}/{contentId}.html
  meta ArticleTitle/PubDate/ContentSource, 正文 div.wzcon.j-fontContent (与 ahshx 一致)
栏目: 徽州区生态环境分局-建设项目环评文件（报告书、报告表）审批 (基层政务公开-生态环境)
  内容: 环评批复/批前公示/受理公示, total=306, 21页
进程锁: flock 站点级串行
"""
import sys, os, re, asyncio, json, fcntl, time
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from crawler_lib import push_to_searchdb

BASE = "https://www.ahhz.gov.cn"
SITE_ID = "6793339"
ORGAN_ID = "6615882"
CAT_ID = "1000260"
SITE_NAME = "徽州区生态环境分局-建设项目环评审批"
LOCK_FILE = "/tmp/ahhz_hpgs.lock"

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] 另一 ahhz 实例运行中, 等待释放 (最多 {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):
    API_TPL = (f"{BASE}/huangshanzwgk/zwgk/site/label/8888?_={{rand}}"
               f"&action=list&labelName=grassrootsContentPageList&siteId={SITE_ID}"
               f"&isDate=true&dateFormat=yyyy-MM-dd&length=50&organId={ORGAN_ID}&catId={CAT_ID}"
               f"&pageSize=15&pageIndex={{page}}&type=4&keyWords=&isSetValue=true&isJson=true&result=")
    LIST_URL = f"{BASE}/zwgk/grassroots/column/{ORGAN_ID}?&catId={CAT_ID}"

    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(LIST_URL, wait_until='domcontentloaded', timeout=35000)
            await page.wait_for_timeout(8000)
            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' 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

        # API 拉列表
        items_all = []
        seen = set()
        total = 0
        for pg in range(1, pages + 1):
            api_url = API_TPL.format(rand=str(abs(hash(f"ahhz_{pg}")))[-15:], page=pg)
            data = await page.evaluate(f"""async () => {{
                try {{
                    const r = await fetch('{api_url}');
                    return await r.json();
                }} catch(e) {{ return {{error: e.message}}; }}
            }}""")
            if 'error' in data:
                print(f"  [API ERR] {data['error']}")
                break
            total = data.get('total', 0)
            items = data.get('data', []) or []
            if not items:
                break
            print(f"  第{pg}页: {len(items)} 条 (total={total})")
            for it in items:
                cid = it.get('contentId')
                if cid and cid not in seen:
                    seen.add(cid)
                    url = f"{BASE}/zwgk/grassroots/{ORGAN_ID}/{cid}.html"
                    items_all.append({
                        'url': url,
                        'title': it.get('title', '').strip(),
                        'date': (it.get('publishDate') or '')[:10],
                    })
            if pg * 15 >= total:
                break

        print(f"  [LIST] total={total}, 去重后 {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(3000)
                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()
            # 正文 wzcon j-fontContent
            content = ""
            m = re.search(r'class="wzcon\s+j-fontContent[^"]*"[^>]*>([\s\S]*?)</div>\s*</div>', html)
            if m:
                content = m.group(1).strip()
            if not content:
                idx2 = html.find('class="wzcon j-fontContent"')
                if idx2 > 0:
                    start = html.find('>', idx2) + 1
                    content = html[start:start+20000]
            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, "ahhz_hpgs")
    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()
