#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""湘潭雨湖区-环境保护 爬虫 (TRS CMS, GB2312编码)"""
import re, sys, os, time
import requests
from bs4 import BeautifulSoup
from urllib.parse import urljoin

BASE_URL = "https://www.xtyh.gov.cn"
LIST_BASE = "https://www.xtyh.gov.cn/2997/3005/20460"
DB_PATH = "/root/search.db"
SITE_NAME = "湘潭雨湖区-环境保护"
TABLE_NAME = "gov_raw"
MAX_PAGES = 5

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",
    "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
    "Accept-Language": "zh-CN,zh;q=0.9",
}


def get_list_url(page):
    if page == 1:
        return f"{LIST_BASE}/index.htm"
    else:
        return f"{LIST_BASE}/index_{page-1}.htm"


def get_list_page(url):
    try:
        r = requests.get(url, headers=HEADERS, timeout=30, verify=False)
        r.encoding = "gb2312"
        if r.status_code == 200 and len(r.text) > 200:
            return r.text
    except Exception as e:
        print(f"  [!] 请求失败: {e}", flush=True)
    return None


def parse_list(html):
    soup = BeautifulSoup(html, "html.parser")
    items = []
    con = soup.select_one("div.gkgd-con")
    if not con:
        return items
    for li in con.find_all("li"):
        a = li.find("a")
        if not a:
            continue
        href = a.get("href", "").strip()
        title = a.get_text(strip=True)
        span = li.find("span")
        date_str = span.get_text(strip=True) if span else ""

        if href and title:
            full_url = urljoin(LIST_BASE + "/", href)
            items.append((title, full_url, date_str))
    return items


def fetch_detail(url):
    try:
        r = requests.get(url, headers=HEADERS, timeout=30, verify=False)
        r.encoding = "gb2312"
        if r.status_code != 200:
            return None, None, None
    except:
        return None, None, None

    soup = BeautifulSoup(r.text, "html.parser")

    # Title
    title_el = soup.find("title")
    title = title_el.get_text(strip=True) if title_el else ""
    # Clean title: remove site name suffix
    title = re.sub(r"[\s_\-]+雨湖区人民政府.*$", "", title).strip()

    # Date from div.xlnk
    pub_date = ""
    for sel in ["div.xlnk", "div.wrap-con", "div.info"]:
        el = soup.select_one(sel)
        if el:
            txt = el.get_text()
            m = re.search(r"(\d{4}-\d{2}-\d{2})", txt)
            if m:
                pub_date = m.group(1)
                break

    # Content
    content = ""
    for sel in ["div.xl-xqnr", "div.TRS_Editor", "div.content", "div.main"]:
        el = soup.select_one(sel)
        if el and len(el.get_text(strip=True)) > 100:
            content = str(el)
            break

    return title, pub_date, content


def main():
    requests.packages.urllib3.disable_warnings()

    import sqlite3
    conn = sqlite3.connect(DB_PATH, timeout=60)
    cur = conn.cursor()

    cur.execute(f"SELECT page_url FROM {TABLE_NAME}")
    existing_urls = set(row[0] for row in cur.fetchall())

    all_items = []
    for page in range(1, MAX_PAGES + 1):
        url = get_list_url(page)
        print(f"[*] 正在获取第{page}页: {url}", flush=True)
        html = get_list_page(url)
        if not html:
            print(f"  [!] 第{page}页为空，跳过", flush=True)
            continue
        items = parse_list(html)
        print(f"  [>] 解析到 {len(items)} 条", flush=True)
        if not items:
            break
        all_items.extend(items)
        time.sleep(0.5)

    print(f"\n[*] 总计获取列表 {len(all_items)} 条", flush=True)

    new_items = [(t, u, d) for t, u, d in all_items if u not in existing_urls]
    print(f"[*] 排除已存在后，新增 {len(new_items)} 条", flush=True)

    if not new_items:
        print("[V] 无新数据需要爬取", flush=True)
        conn.close()
        return

    inserted = 0
    for i, (title, url, date_str) in enumerate(new_items, 1):
        print(f"  [{i}/{len(new_items)}] {title[:40]}...", flush=True)
        det_title, det_date, content = fetch_detail(url)

        final_title = det_title or title
        final_date = det_date or date_str

        if not content or len(content.strip()) < 50:
            print(f"    [!] 内容为空或过短，跳过", flush=True)
            continue

        text_only = BeautifulSoup(content, "html.parser").get_text(strip=True)
        summary = text_only[:200] if text_only else ""

        try:
            cur.execute(
                f"INSERT OR IGNORE INTO {TABLE_NAME} (title, page_url, content, summary, publish_date, site_name) VALUES (?, ?, ?, ?, ?, ?)",
                (final_title, url, content, summary, final_date, SITE_NAME)
            )
            if cur.rowcount > 0:
                inserted += 1
                conn.commit()
        except Exception as e:
            print(f"    [!] 入库失败: {e}", flush=True)

        time.sleep(0.3)

    conn.close()
    print(f"\n[V] 完成！入库 {inserted} 条新数据", flush=True)


if __name__ == "__main__":
    main()
