#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""邛崃市人民政府 - 投资邛崃/园区资讯栏目爬虫
站点: https://qionglai.gov.cn (四川成都)
栏目: /qlsgzxxw/c151247/tzql_list.shtml (投资邛崃, 重定向到园区资讯; 含环评公示)
WAF: 瑞数4代 JS 挑战 (412, $_ts) → Playwright 过挑战; 证书过期须 ignore_https_errors=True
列表: GET /es-search/search/{channeId}?_template=ucap/cdtf&_pageSize=20&page=N
  返回 JSON: {total, page, rows, results:[{title, contentHtml(实体转义需unescape), url, publishedTimeStr}]}
  正文用 API contentHtml (完整); ⚠️ 附件不在 contentHtml 中 → 每条补抓详情页 div#content 提取
channeId aa898b55e2334b39843a39b78612d64d (meta name=column channelid=)
入库: 自动检测 /root/search.db 存在则 INSERT OR IGNORE 直插 gov_raw (FTS 触发器自动同步 gov_search)
运行: python3 crawl_qionglai_tzql.py [--pages=N] [--no-db] [--sync-only]
"""
import json, os, re, sys, time, sqlite3, html as html_lib
from datetime import datetime, timedelta
from playwright.sync_api import sync_playwright

SITE_NAME = "邛崃市-投资邛崃"
BASE = "https://qionglai.gov.cn"
LIST_1 = "https://qionglai.gov.cn/qlsgzxxw/c151247/tzql_list.shtml"
CHANNE_ID = "aa898b55e2334b39843a39b78612d64d"
PAGE_SIZE = 20
TOTAL_PAGES = 20
CUTOFF = (datetime.now() - timedelta(days=3*365)).strftime("%Y-%m-%d")
UA = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36"
OUT = "/tmp/qionglai_tzql.jsonl"
DB_PATH = "/root/search.db"
CATEGORY = "投资邛崃"

def parse_pages_arg():
    """支持 --pages=N 和纯数字"""
    for a in sys.argv[1:]:
        if a.startswith("--pages="):
            return int(a.split("=")[1])
        if a.isdigit():
            return int(a)
    return 0

def clean_title(t):
    t = re.sub(r"^[•··\s]+", "", t or "").strip()
    t = t.replace("\u200b", "").replace("\ufeff", "")
    return t

def clean_content(html):
    """正文清洗: span/font unwrap + 嵌套p扁平化 + o:p清理 + 保留表格"""
    from bs4 import BeautifulSoup
    soup = BeautifulSoup(html, "html.parser")
    for tag in soup.find_all(lambda t: t.name and ":" in t.name):
        tag.decompose()
    for tag in soup.find_all(["span", "font"]):
        tag.unwrap()
    # 只提升含嵌套 p 的外层 p (如 <p 外壳><div><p>段1</p><p>段2</p></div></p>),
    # 保留内层真段落 p — 勿 unwrap 内层 p 否则段落被拍平成一坨 (永丰修复)
    while True:
        nested = [p for p in soup.find_all("p") if p.find("p")]
        if not nested:
            break
        nested[0].unwrap()
    for p in soup.find_all("p"):
        if p.get("style"):
            p.attrs = {"align": p.get("align")} if p.get("align") else {}
    return str(soup)

def fetch_api(page, pn):
    """es-search API 分页"""
    api = f"/es-search/search/{CHANNE_ID}?_template=ucap/cdtf&_pageSize={PAGE_SIZE}&page={pn}"
    for _ in range(2):
        try:
            body = page.evaluate("""async (u) => { const r = await fetch(u); return await r.text(); }""", BASE + api)
            data = json.loads(body.replace('&#34;', '"'))
            return data
        except Exception as e:
            print(f"  API页{pn} 失败: {str(e)[:80]} 重试...", flush=True)
            time.sleep(3)
    return None

def fetch_detail(page, detail_url):
    """fetch 详情页提取附件 (API contentHtml 不含附件区, 附件在详情页 div#content 表格内)"""
    fetch_url = detail_url.replace("http://www.qionglai.gov.cn", BASE)
    for _ in range(2):
        try:
            return page.evaluate("""async (u) => { const r = await fetch(u); return await r.text(); }""", fetch_url)
        except Exception:
            time.sleep(2)
    return None

def extract_attachments(html_frag, detail_url):
    """正文内附件链接: <a href="*.pdf/doc/xls...">, 相对路径绝对化"""
    atts = []
    for m in re.finditer(r'<a[^>]+href="([^"]+)"[^>]*>(.*?)</a>', html_frag, re.I | re.S):
        href, name_html = m.group(1).strip(), m.group(2)
        if not href or href.startswith("javascript"):
            continue
        if re.search(r'\.(pdf|docx?|xlsx?|zip|rar|7z)$', href, re.I):
            name = re.sub(r"<[^>]+>", "", name_html).strip()[:100]
            if href.startswith("/"):
                href = BASE + href
            elif href.startswith("http"):
                pass
            else:
                href = detail_url.rsplit("/", 1)[0] + "/" + href
            atts.append({"name": name or href.split("/")[-1], "url": href})
    seen = set()
    uniq = []
    for a in atts:
        if a["url"] not in seen:
            seen.add(a["url"])
            uniq.append(a)
    return uniq

def push_to_db(results):
    if not results:
        return 0, 0
    if not os.path.exists(DB_PATH):
        print(f"  未发现 {DB_PATH}, 跳过入库 (仅写 JSONL)", flush=True)
        return 0, 0
    conn = sqlite3.connect(DB_PATH, timeout=290)
    conn.execute("PRAGMA busy_timeout=290000")
    added = skipped = 0
    cur = conn.cursor()
    for r in results:
        try:
            cur.execute(
                """INSERT OR IGNORE INTO gov_raw
                   (site_name, source_url, page_url, title, publish_date, content, summary, category, script_name, attachments, group_name, industry)
                   VALUES (?,?,?,?,?,?,?,?,?,?,?,?)""",
                (SITE_NAME, r["url"], r["url"], r["title"], r["pub_date"], r["content"],
                 (r["content"] or "")[:500], CATEGORY, "crawl_qionglai_tzql.py", r["attachments"],
                 r.get("group_name", "四川"), r.get("industry", "other"))
            )
            if cur.rowcount > 0:
                added += 1
            else:
                skipped += 1
        except sqlite3.Error as e:
            print(f"  DB err: {e}", flush=True)
            skipped += 1
        conn.commit()
    conn.close()
    return added, skipped

def main():
    max_pages = parse_pages_arg()
    no_db = "--no-db" in sys.argv
    if "--sync-only" in sys.argv:
        print("sync-only: 抓取+入库一体, 无需单独同步", flush=True)
        return
    print(f"站点: {SITE_NAME} 最大页: {max_pages or '全量'} CUTOFF: {CUTOFF}", flush=True)

    results = []
    stats = {"total_api": 0, "kept": 0, "cutoff": 0, "empty": 0, "att_detail": 0, "att_fail": 0}
    with sync_playwright() as p:
        browser = p.chromium.launch(
            headless=True,
            args=["--no-sandbox", "--disable-blink-features=AutomationControlled", "--disable-dev-shm-usage"])
        ctx = browser.new_context(user_agent=UA, locale="zh-CN", viewport={"width": 1366, "height": 900}, ignore_https_errors=True)
        page = ctx.new_page()

        # 过瑞数挑战
        try:
            page.goto(LIST_1, timeout=60000, wait_until="commit")
        except Exception:
            pass
        passed = False
        for i in range(20):
            page.wait_for_timeout(3000)
            try:
                html = page.content()
            except Exception:
                continue
            if "$_ts" not in html and len(html) > 5000:
                print(f"瑞数挑战通过 {i*3}s", flush=True)
                passed = True
                break
        if not passed:
            print("挑战失败!", flush=True)
            browser.close()
            return

        # API 分页
        total_pages = max_pages if max_pages else TOTAL_PAGES
        cutoff_hit = False
        for pn in range(1, total_pages + 1):
            data = fetch_api(page, pn)
            if not data:
                print(f"  页{pn} API失败", flush=True)
                continue
            results_list = data.get("results", [])
            total = data.get("total", 0)
            if not results_list:
                break
            print(f"  页{pn}/{total_pages} API {len(results_list)} 条 (total {total})", flush=True)
            for r in results_list:
                stats["total_api"] += 1
                title = clean_title(r.get("title", ""))
                pub_date = (r.get("publishedTimeStr") or "")[:10]
                detail_url = r.get("url", "")
                if pub_date and pub_date < CUTOFF:
                    stats["cutoff"] += 1
                    cutoff_hit = True
                    break
                # contentHtml 反转义
                content_html = r.get("contentHtml", "") or ""
                content_html = html_lib.unescape(content_html)
                content = clean_content(content_html) if content_html else ""
                text = re.sub(r"<[^>]+>", "", content).strip()
                if len(text) < 10 and "<img" not in content:
                    print(f"    空正文跳过: {title[:30]}", flush=True)
                    stats["empty"] += 1
                    continue
                # img src 绝对化
                if "<img" in content:
                    content = re.sub(
                        r'(<img[^>]+src=")([^"]+)(")',
                        lambda mm: mm.group(1) + (mm.group(2) if mm.group(2).startswith("http") else (BASE + mm.group(2) if mm.group(2).startswith("/") else detail_url.rsplit("/", 1)[0] + "/" + mm.group(2))) + mm.group(3),
                        content)
                # 附件: 补抓详情页 (API contentHtml 不含附件区)
                atts = []
                detail_html = fetch_detail(page, detail_url)
                if detail_html:
                    stats["att_detail"] += 1
                    atts = extract_attachments(detail_html, detail_url)
                else:
                    stats["att_fail"] += 1
                rec = {
                    "site_name": SITE_NAME,
                    "title": title,
                    "pub_date": pub_date,
                    "content": content,
                    "source_url": detail_url,
                    "url": detail_url,
                    "group_name": "四川",
                    "industry": "other",
                    "attachments": json.dumps(atts, ensure_ascii=False) if atts else "",
                }
                results.append(rec)
                stats["kept"] += 1
            if cutoff_hit:
                print(f"    日期 < CUTOFF 停止", flush=True)
                break
            time.sleep(0.8)

        browser.close()

    save_results(results, stats)
    if not no_db:
        added, skipped = push_to_db(results)
        print(f"=== 入库: 新增{added} 跳过{skipped} ===", flush=True)
    print(f"=== 完成: API{stats['total_api']} 保留{stats['kept']} CUTOFF截{stats['cutoff']} 空{stats['empty']} 详情OK{stats['att_detail']} 详情fail{stats['att_fail']} ===", flush=True)

def save_results(results, stats=None):
    with open(OUT, "w", encoding="utf-8") as f:
        for r in results:
            f.write(json.dumps(r, ensure_ascii=False) + "\n")
    print(f"已写 {len(results)} 条到 {OUT}", flush=True)

if __name__ == "__main__":
    main()
