#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""大英县人民政府 — 通知公告爬虫"""
import requests, sqlite3, re
from bs4 import BeautifulSoup

DB = "/root/search.db"
BASE = "https://www.daying.gov.cn"
LIST_TPL = BASE + "/gongkai/kuozhan/10043.html?page={}"
HEADERS = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 Chrome/120.0.0.0 Safari/537.36"}
SITE = "daying_tzgg"
MAX_PAGES = 35
seen_urls = set()

def extract_detail(url):
    try:
        r = requests.get(url, headers=HEADERS, timeout=30)
        r.encoding = "utf-8"
    except Exception as e:
        print(f"  [ERR] 详情请求失败: {e}")
        return None, None, None
    soup = BeautifulSoup(r.text, "html.parser")
    # 标题
    title = ""
    h1 = soup.find("h1")
    title = h1.get_text(strip=True) if h1 else ""
    # 日期
    date = ""
    mt = soup.find("meta", attrs={"name": "PubDate"})
    if mt:
        d = mt.get("content", "")
        m = re.search(r"(\d{4}-\d{2}-\d{2})", d)
        if m: date = m.group(1)
    if not date:
        sp = soup.find("span", string=re.compile(r"发布时间"))
        if sp:
            m = re.search(r"(\d{4}-\d{2}-\d{2})", sp.get_text())
            if m: date = m.group(1)
    # 正文
    content_div = soup.find("div", class_="xqing-web-box")
    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):
    url = LIST_TPL.format(pg)
    try:
        r = requests.get(url, headers=HEADERS, timeout=30)
        r.encoding = "utf-8"
    except:
        return []
    soup = BeautifulSoup(r.text, "html.parser")
    items = []
    for li in soup.select("ul.content-list > li"):
        a = li.find("a", href=True)
        if not a: continue
        href = a["href"]
        if not href.startswith("http"): href = BASE + href
        title = a.get("title", "") or a.get_text(strip=True)
        if not title or href in seen_urls: continue
        seen_urls.add(href)
        sp = li.find("span")
        date = sp.get_text(strip=True) if sp else ""
        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()
