#!/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 = "http://gxq.xianning.gov.cn"
LIST_BASE = BASE + "/zwgk/fdzdgknr/qtzdgknr/sthjbh"
DB = "/root/search.db"
CUTOFF = datetime.now() - timedelta(days=365 * 3)
SITE_NAME = "咸宁高新区-生态环境"
CATEGORY = "高新区"
UA = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.0.0 Safari/537.36"
HEADERS = {
    "User-Agent": UA,
    "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8",
    "Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8",
}

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):
    items = []
    for li in soup.select("ul.info-list > li"):
        a = li.find("a")
        ds = li.find("span")
        if not a or not ds:
            continue
        href = a.get("href", "").strip()
        title = (a.get("title") or a.get_text(strip=True)).strip()
        date_str = ds.get_text(strip=True)
        try:
            pub_date = datetime.strptime(date_str, "%Y-%m-%d")
        except:
            continue
        if pub_date < CUTOFF:
            return items, True
        url = href if href.startswith("http") else BASE + href
        items.append((title, url, date_str))
    return items, False


def extract_content(soup):
    con = soup.select_one("div.view.TRS_UEDITOR") or soup.select_one("div.con.m15")
    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)
    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 ""
        now = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        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] 开始爬取" % SITE_NAME)
    all_data = []

    for page in range(5):
        if page == 0:
            url = "%s/index.shtml" % LIST_BASE
        else:
            url = "%s/index_%d.shtml" % (LIST_BASE, page)
        print("  第%d页: %s" % (page + 1, url))
        soup = fetch_soup(url)
        if not soup:
            break
        items, stopped = parse_list(soup)
        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)
        conn.execute("INSERT INTO gov_raw_fts(gov_raw_fts) VALUES('rebuild')")
        conn.commit()
        conn.close()

    print("完成!")


if __name__ == "__main__":
    main()
