#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""大邑县人民政府 - 农业农村局公示公告栏目爬虫
站点: https://www.day.gov.cn (dayi 大邑, 非大冶!)
栏目: /day/c116938/nlj_list.shtml (公示公告, 160条/32页)
WAF: 瑞数4代 JS 挑战 (412, $_ts) → Playwright 过挑战后 fetch
列表: nlj_list.shtml + nlj_list_{N}.shtml (N=2..32)
  条目: ul.list_text > li > h6 > a[title] (单/双引号 title) + span.date (YYYY-MM-DD)
详情: fetch → div.details_con h1 标题 + div.details_text 正文 + meta ArticleTitle/PubDate/ContentSource
附件: 正文内 <a href="*.pdf/doc/xls..."> 正则提取 urljoin 绝对化
入库: 自动检测 /root/search.db 存在则 INSERT OR IGNORE 直插 gov_raw (FTS 触发器自动同步 gov_search)
运行: python3 crawl_dayi_gsgg.py [--pages=N] [--no-db] [--sync-only]
"""
import json, os, re, sys, time, sqlite3
from datetime import datetime, timedelta
from playwright.sync_api import sync_playwright

SITE_NAME = "大邑县农业农村局-公示公告"
BASE = "https://www.day.gov.cn"
LIST_1 = "https://www.day.gov.cn/day/c116938/nlj_list.shtml"
TOTAL_PAGES = 32
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/dayi_gsgg.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 extract_attachments(detail_html, detail_url):
    """正文内附件链接: <a href="*.pdf/doc/xls...">"""
    atts = []
    for m in re.finditer(r'<a[^>]+href="([^"]+)"[^>]*>(.*?)</a>', detail_html, 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 not href.startswith("http"):
                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 fetch_ok(page, url):
    """fetch 详情/列表, 失败重试一次"""
    for _ in range(2):
        try:
            return page.evaluate("""async (u) => { const r = await fetch(u); return await r.text(); }""", url)
        except Exception:
            time.sleep(2)
    return None

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_dayi_gsgg.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 = {"list": 0, "detail_ok": 0, "empty": 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})
        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

        # 分页抓列表
        total_fetched = 0
        cutoff_hit = False
        for pn in range(1, TOTAL_PAGES + 1):
            if max_pages and pn > max_pages:
                break
            url = LIST_1 if pn == 1 else f"{BASE}/day/c116938/nlj_list_{pn}.shtml"
            html = fetch_ok(page, url)
            if not html:
                print(f"  页{pn} 列表失败", flush=True)
                continue
            items = re.findall(r'<li>\s*<h6><a href="([^"]+)"[^>]*?title=[\'"]([^\'"]+)[\'"][^>]*?>(.*?)</a></h6>\s*<p></p>\s*<span class="date">([\d-]+)</span>', html, re.S)
            if not items:
                print(f"  页{pn} 无条目 (可能非列表页)", flush=True)
                continue
            print(f"  页{pn}/{TOTAL_PAGES} 列表 {len(items)} 条", flush=True)
            for href, t_title, t_html, date in items:
                title = clean_title(t_title or re.sub(r"<[^>]+>", "", t_html))
                pub_date = date[:10]
                stats["list"] += 1
                if pub_date and pub_date < CUTOFF:
                    print(f"    日期 {pub_date} < CUTOFF 停止", flush=True)
                    cutoff_hit = True
                    break
                # 详情
                detail_url = href if href.startswith("http") else BASE + href
                detail_html = fetch_ok(page, detail_url)
                if not detail_html:
                    print(f"    详情失败: {title[:30]}", flush=True)
                    continue
                stats["detail_ok"] += 1
                # 正文容器 div.details_text
                m = re.search(r'<div[^>]*class="details_text"[^>]*>(.*?)</div>\s*</div>', detail_html, re.S)
                if m:
                    content_html = m.group(1)
                else:
                    # 兜底: details_con 之后
                    m2 = re.search(r'class="details_con[^"]*"[^>]*>(.*?)$', detail_html, re.S)
                    content_html = m2.group(1)[:8000] if m2 else ""
                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)
                atts = extract_attachments(detail_html, detail_url)
                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)
                total_fetched += 1
            if cutoff_hit:
                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"=== 完成: 列表{stats['list']} 详情OK{stats['detail_ok']} 空{stats['empty']} ===", 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()
