#!/usr/bin/env python3
"""
东至县人民政府 - 详细规划（城镇开发边界内）爬虫
CMS: 基层政务公开平台
列表: 静态分页 page_N.html
详情: requests + <div class="m-dttexts" id="zoom"> + <h1 class="u-lgtit">
WAF: 无

运行: python3 crawl_dongzhi.py [--full]
  --full: 全量爬取 (所有6页，含日期过滤)
  不加: 仅爬第1页 (增量模式，日跑用)
"""

import sys, re, time, random, sqlite3, os, urllib.request, urllib.error
import html as htmlmod
from concurrent.futures import ThreadPoolExecutor, as_completed
from datetime import datetime, timedelta

DB_PATH = os.environ.get("SEARCH_DB", "/root/search.db")
SITE_NAME = "东至县人民政府-详细规划（城镇开发边界内）"
SOURCE = "东至县自然资源和规划局"

BASE_URL = "https://www.dongzhi.gov.cn"
HEADERS = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.0.0 Safari/537.36",
}

MAX_PAGES = 6
PAGE_SIZE = 20
NUM_THREADS = 5
REQUEST_DELAY = (0.3, 0.5)

# 3年截点
THREE_YEARS_AGO = (datetime.now() - timedelta(days=365*3)).strftime("%Y-%m-%d")


def log(msg):
    print(f"[{SITE_NAME}] {msg}", flush=True)


def fetch_list(page_no):
    url = f"{BASE_URL}/Jczwgk/opennessList/263/132007002/page_{page_no}.html"
    req = urllib.request.Request(url, headers=HEADERS)
    try:
        resp = urllib.request.urlopen(req, timeout=15)
        return resp.read().decode()
    except Exception as e:
        log(f"列表页 {page_no} 请求失败: {e}")
        return None


def parse_list(html_text):
    items = []
    # <li> <span>date</span> <a href="..." title="...">title</a> </li>
    pattern = re.compile(r"<li>(.*?)</li>", re.DOTALL)
    for li in pattern.findall(html_text):
        date_m = re.search(r"<span[^>]*>(\d{4}-\d{2}-\d{2})</span>", li)
        a_m = re.search(r'<a href="([^"]+)"\s+title="([^"]*)"', li)
        if not a_m:
            a_m = re.search(r'<a href="([^"]+)"[^>]*>([^<]+)</a>', li)
        if not date_m or not a_m:
            continue
        date = date_m.group(1)
        url_path = a_m.group(1)
        title = htmlmod.unescape(a_m.group(2).strip())

        # 3年截点
        if date < THREE_YEARS_AGO:
            continue

        full_url = url_path if url_path.startswith("http") else BASE_URL + url_path
        items.append((full_url, title, date))
    return items


def fetch_detail(url, title, date):
    req = urllib.request.Request(url, headers=HEADERS)
    try:
        resp = urllib.request.urlopen(req, timeout=15)
        html = resp.read().decode()
    except Exception as e:
        return (url, title, date, None, SOURCE)

    # 标题: meta ArticleTitle
    final_title = title
    m = re.search(r'<meta[^>]*ArticleTitle["\s][^>]*content="([^"]*)"', html)
    if m:
        final_title = htmlmod.unescape(m.group(1).strip())

    # 来源: meta ContentSource
    source = SOURCE
    m = re.search(r'<meta[^>]*ContentSource["\s][^>]*content="([^"]*)"', html)
    if m:
        source = htmlmod.unescape(m.group(1).strip())

    # 正文: <div class="m-dttexts" id="zoom">
    content = None
    m = re.search(r'<div class="m-dttexts[^"]*"[^>]*id="zoom"[^>]*>(.*?)</div>\s*</div>', html, re.DOTALL)
    if m:
        content = m.group(1).strip()
    else:
        # fallback: TRS_Editor
        m = re.search(r'<div[^>]*class="[^"]*TRS_Editor[^"]*"[^>]*>(.*?)</div>', html, re.DOTALL)
        if m:
            content = m.group(1).strip()

    if content:
        content = re.sub(r'\s+', ' ', content).strip()

    return (url, final_title, date, content, source)


def save_to_db(articles):
    conn = sqlite3.connect(DB_PATH, timeout=60)
    cursor = conn.cursor()
    inserted = 0
    skipped = 0

    for url, title, date, content, source in articles:
        try:
            cursor.execute(
                """INSERT OR IGNORE INTO gov_raw
                   (site_name, title, page_url, publish_date, source_url, content)
                   VALUES (?, ?, ?, ?, ?, ?)""",
                (SITE_NAME, title, url, date, source, content or ""),
            )
            if cursor.rowcount > 0:
                inserted += 1
            else:
                skipped += 1
        except Exception as e:
            log(f"入库失败: {url[:50]}... {e}")

    conn.commit()
    conn.close()
    return inserted, skipped


def main():
    is_full = "--full" in sys.argv
    log(f"开始{'全量' if is_full else '增量'}爬取 (3年截点: {THREE_YEARS_AGO})...")

    # 第一阶段: 收集列表
    all_items = []
    pages_to_crawl = range(1, MAX_PAGES + 1) if is_full else [1]

    for page_no in pages_to_crawl:
        time.sleep(random.uniform(*REQUEST_DELAY))
        html_text = fetch_list(page_no)
        if html_text is None:
            continue
        items = parse_list(html_text)
        if not items:
            log(f"第 {page_no} 页: 0 条 (全部超出3年)")
            if is_full:
                continue  # keep going, later pages might have nothing
            else:
                break
        log(f"第 {page_no} 页: {len(items)} 条")
        all_items.extend(items)

    log(f"共获取 {len(all_items)} 条列表数据 (3年过滤后)")

    if not all_items:
        log("没有数据，退出")
        return

    # 第二阶段: 多线程详情
    log(f"开始多线程爬取详情 ({NUM_THREADS}线程)...")
    results = []
    with ThreadPoolExecutor(max_workers=NUM_THREADS) as executor:
        futures = {executor.submit(fetch_detail, url, t, d): i for i, (url, t, d) in enumerate(all_items)}
        done = 0
        total = len(futures)
        for f in as_completed(futures):
            done += 1
            try:
                results.append(f.result())
            except Exception:
                idx = futures[f]
                url, t, d = all_items[idx]
                results.append((url, t, d, None, SOURCE))
            if done % 20 == 0 or done == total:
                log(f"详情进度: {done}/{total}")

    # 第三阶段: 入库
    inserted, skipped = save_to_db(results)
    log(f"入库完成: 新增 {inserted}, 跳过 {skipped}")


if __name__ == "__main__":
    main()
