#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""临澧县人民政府 - 公告公示栏目爬虫 (linli.gov.cn /zwyw/gggs)
站点: https://www.linli.gov.cn (湖南常德临澧县, PowerCMS)
栏目: /zwyw/gggs (政务要闻 > 公告公示, 2009条/101页)
列表: ul.newsList > li > span.date + a[href][title], 分页 /zwyw/gggs_{N}
详情: div.conTxt 正文 + meta ArticleTitle/PubDate
附件: 正文内 <a href="*.pdf/doc/xls..."> 正则提取 urljoin 绝对化
入库: INSERT OR IGNORE 直插 gov_raw (FTS 触发器自动同步 gov_search)
运行: python3 crawl_linli_gggs.py [--pages=N]
"""
import json, os, re, sys, time, sqlite3
import requests
from datetime import datetime, timedelta
from bs4 import BeautifulSoup

SITE_NAME = "临澧县-公告公示"
BASE = "https://www.linli.gov.cn"
LIST_URL = BASE + "/zwyw/gggs"
TOTAL_PAGES = 101
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/125.0.0.0 Safari/537.36"
OUT = "/tmp/linli_gggs.jsonl"
DB_PATH = "/root/search.db"
CATEGORY = "公告公示"
GROUP_NAME = "湖南"

HEADERS = {
    "User-Agent": UA,
    "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
    "Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8",
}


def parse_pages_arg():
    for a in sys.argv[1:]:
        if a.startswith("--pages="):
            return int(a.split("=")[1])
        if a.isdigit():
            return int(a)
    return 0


def fetch(url, retries=3):
    for attempt in range(retries):
        try:
            r = requests.get(url, headers=HEADERS, timeout=30)
            r.encoding = "utf-8"
            if r.status_code == 403:
                if attempt < retries - 1:
                    time.sleep(30)
                    continue
                print(f"  [WAF-403] {url}", flush=True)
                return None
            return r.text
        except Exception as e:
            if attempt < retries - 1:
                time.sleep(2)
                continue
            print(f"  [ERROR] {url}: {e}", flush=True)
            return None


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清理 + 保留表格"""
    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 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_linli_gggs.py", r["attachments"],
                 r.get("group_name", 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()
    print(f"站点: {SITE_NAME} 最大页: {max_pages or '全量'} CUTOFF: {CUTOFF}", flush=True)

    results = []
    stats = {"list": 0, "detail_ok": 0, "empty": 0}
    cutoff_hit = False

    for pn in range(1, TOTAL_PAGES + 1):
        if max_pages and pn > max_pages:
            break
        url = LIST_URL if pn == 1 else f"{LIST_URL}_{pn}"
        html = fetch(url)
        if not html:
            print(f"  页{pn} 列表失败", flush=True)
            continue
        soup = BeautifulSoup(html, "html.parser")
        lis = soup.select("ul.newsList > li")
        if not lis:
            print(f"  页{pn} 无条目", flush=True)
            continue
        page_items = 0
        for li in lis:
            a = li.find("a")
            date_span = li.find("span", class_="date")
            if not a or not date_span:
                continue
            href = a.get("href", "")
            if href.startswith("http") and BASE not in href:
                continue
            title = clean_title(a.get("title", "") or a.get_text(strip=True))
            date_str = date_span.get_text(strip=True)
            if not re.match(r"^\d{4}-\d{2}-\d{2}$", date_str):
                continue
            if date_str < CUTOFF:
                print(f"    日期 {date_str} < CUTOFF 停止", flush=True)
                cutoff_hit = True
                break
            detail_url = href if href.startswith("http") else BASE + href
            stats["list"] += 1
            page_items += 1

            detail_html = fetch(detail_url)
            if not detail_html:
                print(f"    详情失败: {title[:30]}", flush=True)
                continue
            stats["detail_ok"] += 1
            dsoup = BeautifulSoup(detail_html, "html.parser")
            con = dsoup.select_one("div.conTxt")
            content = clean_content(str(con)) if con 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)
            # meta PubDate 兜底
            pub_date = date_str
            m = re.search(r'<meta[^>]+name="PubDate"[^>]+content="([^"]+)"', detail_html)
            if m and m.group(1)[:10] >= date_str:
                pub_date = m.group(1)[:10]
            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": GROUP_NAME,
                "industry": "other",
                "attachments": json.dumps(atts, ensure_ascii=False) if atts else "",
            }
            results.append(rec)
        if cutoff_hit:
            break
        print(f"  页{pn}/{TOTAL_PAGES} 列表 {page_items} 条 (累计 {len(results)})", flush=True)
        time.sleep(15)

    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)

    added, skipped = push_to_db(results)
    print(f"=== 入库: 新增{added} 跳过{skipped} ===", flush=True)
    print(f"=== 完成: 列表{stats['list']} 详情OK{stats['detail_ok']} 空{stats['empty']} ===", flush=True)


if __name__ == "__main__":
    main()
