#!/usr/bin/env python3
"""蚌埠市生态环境局-项目受理情况 爬虫"""
import requests
import re
import os
import sys
from bs4 import BeautifulSoup

SEARCH_DB = os.getenv("SEARCH_DB", "/root/search.db")
SITE_NAME = "蚌埠市生态环境局-项目受理情况"
BASE_URL = "https://sthjj.bengbu.gov.cn"
COLUMN_ID = "6814211"
TOTAL_ITEMS = 572
PAGE_SIZE = 15
TOTAL_PAGES = 39

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"
}


def parse_list_page(html):
    """解析列表页HTML，返回 [(title, url, date_str), ...]"""
    items = []
    soup = BeautifulSoup(html, "html.parser")
    ul = soup.find("ul", class_=re.compile(r"doc_list"))
    if not ul:
        return items
    for li in ul.find_all("li"):
        a = li.find("a")
        if not a:
            continue
        href = a.get("href", "")
        title = a.get("title", "") or a.get_text(strip=True)
        if not href or not title:
            continue
        # Full URL
        if href.startswith("http"):
            detail_url = href
        else:
            detail_url = BASE_URL + href

        # Date
        date_span = li.find("span", class_="date")
        date_str = date_span.get_text(strip=True) if date_span else ""

        items.append((title, detail_url, date_str))
    return items


def parse_detail(html):
    """解析详情页，返回 (title, content, publish_date)"""
    soup = BeautifulSoup(html, "html.parser")

    # Title from <h1 class="newstitle">
    title = ""
    h1 = soup.find("h1", class_="newstitle")
    if h1:
        title = h1.get_text(strip=True)

    # Date from meta tag or info bar
    publish_date = ""
    # First try meta tag
    meta = soup.find("meta", attrs={"name": "PubDate"})
    if meta and meta.get("content"):
        m = re.search(r'(\d{4}-\d{2}-\d{2})', meta["content"])
        if m:
            publish_date = m.group(1)
    if not publish_date:
        # Try info bar
        info_div = soup.find("div", class_="newsinfo")
        if info_div:
            text = info_div.get_text()
            m = re.search(r'(\d{4}-\d{2}-\d{2})', text)
            if m:
                publish_date = m.group(1)

    # Content from <div class="j-fontContent newscontnet minh300">
    content = ""
    content_div = soup.find("div", class_="j-fontContent")
    if content_div:
        content = str(content_div)

    return title, content, publish_date


def crawl():
    conn = None
    try:
        import sqlite3
        conn = sqlite3.connect(SEARCH_DB)
        c = conn.cursor()
        c.execute('''CREATE TABLE IF NOT EXISTS gov_raw (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            title TEXT,
            content TEXT,
            source_url TEXT UNIQUE,
            site_name TEXT,
            publish_date TEXT
        )''')

        total_new = 0
        total_skipped = 0

        for page in range(1, TOTAL_PAGES + 1):
            if page == 1:
                page_url = f"{BASE_URL}/hbyw/hpsp/hjyxpj/xmslqk/index.html"
            else:
                page_url = f"{BASE_URL}/content/column/{COLUMN_ID}?pageIndex={page}"

            try:
                resp = requests.get(page_url, headers=HEADERS, timeout=30)
                resp.encoding = "utf-8"
            except Exception as e:
                print(f"第{page}页请求失败: {e}")
                continue

            items = parse_list_page(resp.text)
            print(f"第{page}/{TOTAL_PAGES}页: {len(items)}条")

            for i, (title, detail_url, date_from_list) in enumerate(items, 1):
                # Check if exists
                c.execute("SELECT id FROM gov_raw WHERE source_url = ?", (detail_url,))
                if c.fetchone():
                    total_skipped += 1
                    continue

                # Fetch detail
                try:
                    dr = requests.get(detail_url, headers=HEADERS, timeout=30)
                    dr.encoding = "utf-8"
                except Exception as e:
                    print(f"  [{i}/{len(items)}] ❌ 详情失败: {e}")
                    continue

                _, content, publish_date = parse_detail(dr.text)
                if not publish_date:
                    publish_date = date_from_list

                try:
                    c.execute(
                        "INSERT OR IGNORE INTO gov_raw (title, content, source_url, site_name, publish_date) VALUES (?, ?, ?, ?, ?)",
                        (title, content, detail_url, SITE_NAME, publish_date)
                    )
                    conn.commit()
                    total_new += 1
                    content_len = len(content) if content else 0
                    status = " ⚠️ 内容过短" if content_len < 200 else ""
                    print(f"  [{i}/{len(items)}] ✅ {title[:35]}... ({publish_date}){status}")
                except Exception as e:
                    print(f"  [{i}/{len(items)}] ❌ 入库失败: {e}")

        print(f"\n✅ 爬取完成！新增: {total_new}, 跳过(已存在): {total_skipped}")
        c.execute("SELECT COUNT(*) FROM gov_raw WHERE site_name = ?", (SITE_NAME,))
        total = c.fetchone()[0]
        print(f"  共 {total} 条")

    finally:
        if conn:
            conn.close()


if __name__ == "__main__":
    crawl()
