#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""爬取常宁市 - 通知公告"""
import requests
import sqlite3
import re
import sys
import time
from datetime import datetime, timedelta
from bs4 import BeautifulSoup

BASE = "https://www.hnchangning.gov.cn/zwgk/szfxxgkml/tzgg"
DB = "/root/search.db"
CUTOFF = datetime.now() - timedelta(days=365 * 3)
SITE_NAME = "常宁市-通知公告"
CATEGORY = "县区"
MAX_PAGES = 5

UA = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36"
HEADERS = {"User-Agent": UA, "Accept": "text/html,*/*;q=0.8", "Accept-Language": "zh-CN,zh;q=0.9"}

s = requests.Session()
s.headers.update(HEADERS)


def fetch_soup(url, retries=3):
    for attempt in range(retries):
        try:
            r = s.get(url, timeout=30)
            r.encoding = "utf-8"
            return BeautifulSoup(r.text, "html.parser")
        except Exception as e:
            if attempt < retries - 1:
                time.sleep(2)
                continue
            print("  [ERROR] %s: %s" % (url, e), file=sys.stderr)
            return None


def parse_list(soup, cutoff_date):
    items = []
    ul = soup.select_one("ul.contain_ul")
    if not ul:
        return items, False
    for li in ul.find_all("li"):
        a = li.find("a")
        date_span = li.find("span", class_="titleDate")
        if not a or not date_span:
            continue
        href = a.get("href", "").strip()
        title = a.get_text(strip=True)
        if not title or not href:
            continue
        date_str = date_span.get_text(strip=True)
        try:
            pub_date = datetime.strptime(date_str, "%Y-%m-%d")
        except:
            continue
        if pub_date < cutoff_date:
            return items, True
        url = href if href.startswith("http") else BASE + "/" + href.lstrip("/")
        items.append((title, url, date_str))
    return items, False


def extract_content(soup):
    con = soup.select_one("div.inner_box")
    if not con:
        # fallback to inner_details
        con = soup.select_one("div.inner_details")
    if not con:
        return ""
    for tag in con.find_all(["script", "style"]):
        tag.decompose()
    return re.sub(r"\s+", " ", str(con)).strip()


def save_to_db(items_data):
    conn = sqlite3.connect(DB, timeout=60)
    c = conn.cursor()
    new_count = 0
    for title, url, date_str, content in items_data:
        c.execute("SELECT id FROM gov_raw WHERE page_url = ?", (url,))
        if c.fetchone():
            continue
        summary = content[:300] if content else ""
        c.execute(
            "INSERT INTO gov_raw (site_name, category, title, page_url, content, summary, publish_date) VALUES (?, ?, ?, ?, ?, ?, ?)",
            (SITE_NAME, CATEGORY, title, url, content, summary, date_str),
        )
        new_count += 1
    conn.commit()
    conn.close()
    return new_count


def main():
    print("[%s] 开始爬取（前%d页）" % (SITE_NAME, MAX_PAGES))
    all_data = []

    for page in range(1, MAX_PAGES + 1):
        if page == 1:
            url = BASE + "/index.html"
        else:
            url = BASE + "/pages/%d.html" % page
        print("  第%d页: %s" % (page, url))
        soup = fetch_soup(url)
        if not soup:
            break
        items, stopped = parse_list(soup, CUTOFF)
        print("    找到 %d 条" % len(items))
        if not items:
            print("    空页，停止")
            break
        for title, item_url, date_str in items:
            print("    详情: %s..." % title[:35])
            detail_soup = fetch_soup(item_url)
            if not detail_soup:
                continue
            content = extract_content(detail_soup)
            if not content:
                print("      [SKIP] 无正文")
                continue
            print("      正文长度: %d" % len(content))
            all_data.append((title, item_url, date_str, content))
            time.sleep(0.5)
        if stopped:
            print("  遇到超3年旧数据，停止")
            break
        time.sleep(1)

    if not all_data:
        print("无新数据")
        return

    print("\n入库 %d 条..." % len(all_data))
    n = save_to_db(all_data)
    print("新增入库: %d 条" % n)

    if n > 0:
        print("重建FTS索引...")
        conn = sqlite3.connect(DB, timeout=60)
        conn.commit()
        conn.close()

    print("完成!")


if __name__ == "__main__":
    main()
