#!/usr/bin/env python3
"""
阜新市细河区人民政府-便民通知 (www.fxxh.gov.cn)
===========================================
列表: /channel/list/11354.html, 11354_{n}.html (pages 2-10), newslist.thtml (pages 11+)
详情: /content/2026/1074549.html, <div id="Detailcontent" class="Detailcontent_inner"> 含正文

用法:
    python3 crawl_fxxh_bmtz.py          # 全量(19页)
    python3 crawl_fxxh_bmtz.py --test   # 测试 5 条
"""

import re, sys, os, time
from datetime import datetime, timedelta, timezone
import requests, urllib3
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)

SITE_NAME  = "细河区-便民通知"
LIST_BASE  = "https://www.fxxh.gov.cn/channel/list/11354"
LIST_DYN   = "https://www.fxxh.gov.cn/newslist.thtml"
SEARCH_DB  = "/root/search.db"
MAX_PAGES  = 19
CUTOFF     = (datetime.now(timezone.utc) - timedelta(days=365*3)).strftime("%Y-%m-%d")
HEADERS    = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36"}

def fetch_list(page):
    if page == 1:
        url = f"{LIST_BASE}.html"
    elif page <= 10:
        url = f"{LIST_BASE}_{page}.html"
    else:
        url = f"{LIST_DYN}?id=11354&pn={page}"
    try:
        r = requests.get(url, headers=HEADERS, timeout=20, verify=False)
        r.encoding = "utf-8"
        return r.text
    except Exception as e:
        print(f"  ! list page {page} fail: {str(e)[:60]}")
        return None

def parse_list(html):
    items = []
    for m in re.finditer(
        r'<a class="list1-ul-link"[^>]*href="([^"]+)"[^>]*>'
        r'.*?<div class="list1-ul-link-inner">([^<]+)'
        r'.*?tabs2Right-part2">\s*(\d{4}-\d{2}-\d{2})',
        html, re.DOTALL
    ):
        url = m.group(1)
        if not url.startswith("http"):
            url = "https://www.fxxh.gov.cn" + url if url.startswith("/") else "https://www.fxxh.gov.cn/" + url
        title = m.group(2).strip()
        pub_date = m.group(3)
        items.append({"title": title, "url": url, "pub_date": pub_date})
    return items

def fetch_detail(url):
    try:
        r = requests.get(url, headers=HEADERS, timeout=20, verify=False)
        r.encoding = "utf-8"
        html = r.text
        # Content in <div id="Detailcontent" class="Detailcontent_inner">
        m = re.search(r'<div id="Detailcontent"[^>]*>(.*?)</div>', html, re.DOTALL)
        if m:
            content = m.group(1)
            content = re.sub(r'<script[^>]*>.*?</script>', '', content, flags=re.DOTALL|re.I)
            content = re.sub(r'<style[^>]*>.*?</style>', '', content, flags=re.DOTALL|re.I)
            return content.strip()
        return ""
    except Exception as e:
        print(f"  ! detail fail: {str(e)[:60]}")
        return ""

def to_db(items):
    if not items:
        return 0, 0
    import sqlite3
    db = sqlite3.connect(SEARCH_DB, timeout=60)
    db.execute("PRAGMA journal_mode=WAL")
    db.execute("PRAGMA synchronous=NORMAL")
    ok, fail = 0, 0
    for it in items:
        try:
            db.execute(
                "INSERT OR REPLACE INTO gov_raw (site_name, title, page_url, content, publish_date, summary, tags, script_name) VALUES (?,?,?,?,?,?,?, 'crawl_fxxh_bmtz.py')",
                (
                    SITE_NAME,
                    (it.get("title") or "")[:500],
                    it.get("url", ""),
                    it.get("content", ""),
                    (it.get("pub_date") or "")[:10],
                    "",
                    "便民通知",
                )
            )
            if db.total_changes > 0:
                ok += 1
            else:
                fail += 1
        except Exception as e:
            fail += 1
    # 2026-09-22: 先提交 gov_raw —— 库上触发器已维护 FTS，下面这条手动写入会因
    #   rowid 重复而 IntegrityError；不先 commit 会把 gov_raw 那条一并回滚（静默丢数据）
    db.commit()
    db.execute(
        "INSERT OR REPLACE INTO gov_search(rowid, title, site_name, summary) "
        "SELECT r.id, r.title, r.site_name, r.summary "
        "FROM gov_raw r WHERE r.id NOT IN (SELECT rowid FROM gov_search) AND r.site_name=?",
        (SITE_NAME,)
    )
    db.commit()
    db.close()
    return ok, fail

def crawl(test=False):
    all_items = []
    seen_urls = set()
    max_p = 5 if test else MAX_PAGES
    for page in range(1, max_p + 1):
        html = fetch_list(page)
        if not html:
            break
        items = parse_list(html)
        if not items:
            print(f"  [Page {page}] empty, reached end")
            break
        new = 0
        for item in items:
            if item["url"] in seen_urls:
                continue
            seen_urls.add(item["url"])
            if item["pub_date"] and item["pub_date"] < CUTOFF:
                continue
            all_items.append(item)
            new += 1
        f = items[0]["pub_date"] if items else "?"
        l = items[-1]["pub_date"] if items else "?"
        print(f"  [Page {page}] {len(items)} items ({f} ~ {l}), new: {new}")
        if new == 0:
            break
    print(f"  Total: {len(all_items)} items within 3yr")
    if test:
        all_items = all_items[:5]
        print(f"  TEST mode: {len(all_items)} items")
    if not all_items:
        return 0, 0
    for i, item in enumerate(all_items):
        print(f"  [{i+1}/{len(all_items)}] {item['title'][:40]}... ", end="", flush=True)
        content = fetch_detail(item["url"])
        item["content"] = content
        print(f"{len(content)}B")
    ok, fail = to_db(all_items)
    return ok, fail

if __name__ == "__main__":
    test = "--test" in sys.argv
    mode = "TEST" if test else "FULL"
    print()
    print(f"[{SITE_NAME}] {mode}")
    t0 = time.time()
    ok, fail = crawl(test=test)
    print(f"  Time: {round(time.time()-t0, 1)}s")
    print(f"  New: {ok} Skip: {fail}")
