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

DB = "/root/search.db"
BASE = "http://www.huangling.gov.cn"
LIST_TPL = BASE + "/xwzx/gsgg/{}.html"
HEADERS = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 Chrome/120.0.0.0 Safari/537.36"}
SITE = "huangling_gsgg"
MAX_PAGES = 20
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 = ""
    tt = soup.select_one("div.m-txt-tt")
    if tt:
        title = tt.get_text(strip=True)
    if not title:
        mt = soup.find("meta", attrs={"name": "ArticleTitle"})
        if mt:
            title = mt.get("content", "")
    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)
    content_tag = soup.find("div", class_="m-txt-article")
    content = ""
    if content_tag:
        for tag in content_tag.find_all(["p", "div"]):
            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("div.m-lst36 > ul > 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, "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()
