#!/usr/bin/env python3
"""爬取 xiushui.gov.cn - 城投集团通知公告"""
import requests
from bs4 import BeautifulSoup
import sqlite3
import os
import re
from datetime import datetime

BASE_URL = "https://www.xiushui.gov.cn"
LIST_PATH = "/xsctgg/ctgg/"
SITE_NAME = "xiushui.gov.cn-城投集团通知公告"
CUTOFF_DATE = "2023-06-16"
DB_PATH = os.getenv("SEARCH_DB", "/root/search.db")

HEADERS = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36",
}

def get_total_pages():
    """解析第一页的 createPageHTML 调用获取总页数"""
    url = BASE_URL + LIST_PATH
    resp = requests.get(url, headers=HEADERS, timeout=30)
    resp.encoding = "utf-8"
    m = re.search(r'createPageHTML\((\d+)', resp.text)
    return int(m.group(1)) if m else 1

def get_list_page(page):
    """获取某一页的文章列表"""
    if page == 1:
        url = BASE_URL + LIST_PATH
    else:
        url = f"{BASE_URL}/xsctgg/ctgg/index_{page-1}.html"
    resp = requests.get(url, headers=HEADERS, timeout=30)
    resp.encoding = "utf-8"
    soup = BeautifulSoup(resp.text, "html.parser")
    items = []
    for li in soup.select("ul.NewsList > li"):
        a = li.find("a")
        span = li.find("span")
        if not a or not span:
            continue
        href = a.get("href", "")
        if href and not href.startswith("http"):
            # URL like ./202606/t20260622_7260215.html
            href = BASE_URL + "/xsctgg/ctgg/" + href.lstrip("./")
        title = a.get("title", a.get_text(strip=True))
        pub_date = span.get_text(strip=True)
        # Filter out separator li.b
        if not title or not href:
            continue
        items.append({"title": title, "url": href, "publish_date": pub_date})
    return items

def get_detail(url):
    """获取详情页的正文HTML"""
    resp = requests.get(url, headers=HEADERS, timeout=30)
    resp.encoding = "utf-8"
    soup = BeautifulSoup(resp.text, "html.parser")
    
    content_parts = []
    # 正文 - TRS编辑器 或 Article_zw
    for sel in ["div.view.TRS_UEDITOR", "div.Article_zw"]:
        div = soup.select_one(sel)
        if div:
            # 补全附件链接
            for a in div.find_all("a"):
                href = a.get("href", "")
                if href and not href.startswith("http"):
                    a["href"] = BASE_URL + href
            content_parts.append(str(div))
            break
    
    if content_parts:
        return "".join(content_parts)
    return ""

def crawl():
    conn = sqlite3.connect(DB_PATH)
    c = conn.cursor()
    
    c.execute("""
        CREATE TABLE IF NOT EXISTS gov_raw (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            title TEXT,
            page_url TEXT UNIQUE,
            content TEXT,
            publish_date TEXT,
            site_name TEXT DEFAULT '',
            crawl_time TEXT DEFAULT (datetime('now', '+8 hours')),
            similar TEXT
        )
    """)
    conn.commit()
    
    total_pages = get_total_pages()
    print(f"总页数: {total_pages}")
    
    total_added = 0
    total_skipped = 0
    cutoff_reached = False
    
    for page in range(1, total_pages + 1):
        if cutoff_reached:
            break
        print(f"  第{page}页...")
        items = get_list_page(page)
        for item in items:
            pub = item["publish_date"]
            if pub and pub < CUTOFF_DATE:
                cutoff_reached = True
                print(f"    截止日期 {CUTOFF_DATE} (当前 {pub})，跳过后续")
                break
            
            c.execute("SELECT id FROM gov_raw WHERE page_url = ?", (item["url"],))
            if c.fetchone():
                total_skipped += 1
                continue
            
            content = get_detail(item["url"])
            if not content:
                print(f"    警告: 空正文 {item['title'][:30]}")
                total_skipped += 1
                continue
            
            c.execute(
                "INSERT OR IGNORE INTO gov_raw (title, page_url, content, publish_date, site_name) VALUES (?, ?, ?, ?, ?)",
                (item["title"], item["url"], content, pub, SITE_NAME)
            )
            if c.rowcount > 0:
                total_added += 1
            conn.commit()
        
        if cutoff_reached:
            break
    
    conn.close()
    print(f"完成: 新增 {total_added} 条, 跳过 {total_skipped} 条")

if __name__ == "__main__":
    crawl()
