#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""仙桃市生态环境局 — 公示公告爬虫"""
import requests, sqlite3, re
from bs4 import BeautifulSoup

DB = "/root/search.db"
BASE = "https://www.xiantao.gov.cn"
LIST_TPL = BASE + "/bmxxgk/shbj/zfxxgk/fdzdgknr/qtzdgknr_37950/gsgg/index{}.shtml"
HEADERS = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 Chrome/120.0.0.0 Safari/537.36"}
SITE = "xiantao_gsgg"
# createPageHTML(20, 0, "index", "shtml", "pages clearfix", 311) -> 16 pages
MAX_PAGES = 20
seen_urls = set()

def extract_detail(url):
    try:
        r = requests.get(url, headers=HEADERS, timeout=30)
        r.encoding = "utf-8"
    except:
        return None, None, None
    soup = BeautifulSoup(r.text, "html.parser")
    # 标题
    title = ""
    tt = soup.select_one("div.xl_tit")
    if tt:
        title = tt.get_text(strip=True)
    # 日期
    date = ""
    for td in soup.find_all("td"):
        if "发文日期" in td.get_text():
            nxt = td.find_next_sibling("td")
            if nxt:
                m = re.search(r"(\d{4}-\d{2}-\d{2})", nxt.get_text())
                if m: date = m.group(1); break
    # 正文 - TRS UEditor
    content_div = soup.find("div", class_="view") or soup.find("div", class_="TRS_Editor")
    content = ""
    if content_div:
        for tag in content_div.find_all(["p", "div", "table"]):
            txt = str(tag).strip()
            if txt: content += txt + "\n"
        content = content.strip()
    return title, date, content

def crawl_page(pg):
    if pg == 1:
        url = LIST_TPL.format("")
    else:
        url = LIST_TPL.format(f"_{pg}")
    try:
        r = requests.get(url, headers=HEADERS, timeout=30)
        r.encoding = "utf-8"
    except:
        return [], 0
    soup = BeautifulSoup(r.text, "html.parser")
    items = []
    # All <a> with href containing /gsgg/ and pointing to shbj
    for a in soup.find_all("a", href=True):
        href = a["href"]
        if "/shbj/" not in href or "/gsgg/" not in href:
            continue
        if not href.startswith("http"):
            href = BASE + href
        if href in seen_urls:
            continue
        seen_urls.add(href)
        title = a.get("title", "") or a.get_text(strip=True)
        # Date is inside <span> within <a>
        sp = a.find("span")
        date = sp.get_text(strip=True) if sp else ""
        # Clean title - remove the date span text
        if sp:
            title = title.replace(sp.get_text(strip=True), "").strip()
        items.append({"title": title.strip(), "url": href, "date": date})
    return items

def main():
    conn = sqlite3.connect(DB)
    conn.execute("PRAGMA journal_mode=WAL")
    c = conn.cursor()
    c.execute("CREATE VIRTUAL TABLE IF NOT EXISTS gov_search_v3 USING fts5(title, content, source_url, publish_date, site_name, tokenize='trigram')")
    
    total_new = total_dup = total_skip = 0
    for pg in range(1, MAX_PAGES + 1):
        print(f"--- 第{pg}页 ---")
        items = crawl_page(pg)
        if not items:
            print("无结果，停止翻页"); break
        print(f"找到{len(items)}条")
        for item in items:
            c.execute("SELECT id FROM gov_raw WHERE page_url=?", (item["url"],))
            if c.fetchone():
                total_dup += 1; continue
            print(f"  [{item['date']}] {item['title'][:50]}")
            title, date, content = extract_detail(item["url"])
            if not title: title = item["title"]
            if not date: date = item["date"]
            if not content or len(content) < 200:
                print(f"    正文过短({len(content) if content else 0}), 跳过")
                total_skip += 1; continue
            summary = re.sub(r"<[^>]+>", "", content)[:200]
            summary = re.sub(r"\s+", " ", summary).strip()
            try:
                c.execute("INSERT INTO gov_raw (title, summary, content, page_url, publish_date, site_name) VALUES (?,?,?,?,?,?)",
                    (title, summary, content, item["url"], date, SITE))
                c.execute("INSERT INTO gov_search_v3 (title, content, source_url, publish_date, site_name) VALUES (?,?,?,?,?)",
                    (title, content, item["url"], date, SITE))
                conn.commit()
                total_new += 1
            except sqlite3.IntegrityError:
                total_dup += 1
    print(f"\n新增: {total_new}  重复: {total_dup}  过短: {total_skip}  总计: {total_new+total_dup+total_skip}")

if __name__ == "__main__":
    main()
