#!/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.cqqj.gov.cn/bm/qfzggw/zwgk_58285/zfxxgkml/jczwgk/zdjsxm/pzjgxx/yxpjsp"
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 (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, cutoff_date):
    items = []
    for li in soup.select("ul.gl-list > li"):
        a = li.find("a")
        date_span = li.find("span")
        if not a or not date_span:
            continue
        href = a.get("href", "").strip()
        title = a.get("title", "").strip()
        if not title:
            title = a.get_text(strip=True)
        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
        # Resolve relative URL
        if href.startswith("./"):
            url = BASE + href[1:]
        elif href.startswith("http"):
            url = href
        else:
            url = BASE + "/" + href.lstrip("/")
        items.append((title, url, date_str))
    return items, False


def extract_content(soup):
    con = soup.select_one("div.trs_editor_view.TRS_UEDITOR")
    if not con:
        con = soup.select_one("div.zwxl-content")
    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(0, MAX_PAGES):
        if page == 0:
            url = BASE + "/"
        else:
            url = BASE + "/index_%d.html" % page
        print("  第%d页: %s" % (page + 1, 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()
