#!/usr/bin/env python3
"""爬取 yyx.gov.cn - 建设项目环境影响评价"""
import requests
from bs4 import BeautifulSoup
import sqlite3
import os
import re
from datetime import datetime

BASE_URL = "https://www.yyx.gov.cn"
LIST_PATH = "/37584/38152/62573/62585/62588/index.htm"
SITE_NAME = "yyx.gov.cn-建设项目环境影响评价"
CUTOFF_DATE = "2023-06-16"
DB_PATH = os.getenv("SEARCH_DB", "/root/search.db")

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 get_last_page():
    """获取总页数"""
    url = BASE_URL + LIST_PATH
    resp = requests.get(url, headers=HEADERS, timeout=30)
    resp.encoding = "gbk"
    html = resp.text
    # 找最后一页链接: index_34.htm 或带offset的
    m = re.search(r"index\.jsp\?pager\.offset=(\d+)", html)
    if m:
        offset = int(m.group(1))
        # offset = (page-1) * per_page, assume 20 per page
        return offset // 20 + 1
    # 找 index_X.htm 中最大的X
    pages = re.findall(r"index_(\d+)\.htm", html)
    if pages:
        return max(int(p) for p in pages) + 1
    return 1

def get_list_page(page):
    """获取某一页的文章列表"""
    if page == 1:
        url = BASE_URL + LIST_PATH
    else:
        url = f"{BASE_URL}/37584/38152/62573/62585/62588/index_{page-1}.htm"
    resp = requests.get(url, headers=HEADERS, timeout=30)
    resp.encoding = "gbk"
    soup = BeautifulSoup(resp.text, "html.parser")
    items = []
    for li in soup.select("ul.news-list-wrapper li.entry-wrapper"):
        a = li.select_one("div.title a")
        date_div = li.select_one("div.date")
        if not a:
            continue
        href = a.get("href", "")
        if href and not href.startswith("http"):
            href = BASE_URL + "/37584/38152/62573/62585/62588/" + href
        title = a.get("title", a.get_text(strip=True))
        pub_date = date_div.get_text(strip=True) if date_div else ""
        items.append({"title": title, "url": href, "publish_date": pub_date})
    return items

def get_detail(url):
    """获取详情页的正文HTML"""
    resp = requests.get(url, headers=HEADERS, timeout=30)
    resp.encoding = "gbk" 
    soup = BeautifulSoup(resp.text, "html.parser")
    
    # 正文区域
    content_div = soup.select_one("div.detail-content-wrapper.p-4")
    if content_div:
        # 补全附件链接
        for a in content_div.find_all("a"):
            href = a.get("href", "")
            if href and not href.startswith("http"):
                a["href"] = BASE_URL + href
        return str(content_div)
    
    return ""

def crawl():
    conn = sqlite3.connect(DB_PATH, timeout=60)
    c = conn.cursor()
    
    c.execute("""
        CREATE TABLE IF NOT EXISTS gov_raw (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            title TEXT,
            page_url TEXT UNIQUE,
            content TEXT,
            publish_date TEXT,
            site_name TEXT DEFAULT '',
            crawl_time TEXT DEFAULT (datetime('now', '+8 hours')),
            similar TEXT
        )
    """)
    conn.commit()
    
    total_pages = get_last_page()
    print(f"总页数: {total_pages}")
    
    total_added = 0
    total_skipped = 0
    cutoff_reached = False
    
    for page in range(1, total_pages + 1):
        if cutoff_reached:
            break
        print(f"  第{page}页...")
        items = get_list_page(page)
        for item in items:
            pub = item["publish_date"]
            if pub and pub < CUTOFF_DATE:
                cutoff_reached = True
                print(f"    截止日期 {CUTOFF_DATE} (当前 {pub})，跳过后续")
                break
            
            c.execute("SELECT id FROM gov_raw WHERE page_url = ?", (item["url"],))
            if c.fetchone():
                total_skipped += 1
                continue
            
            content = get_detail(item["url"])
            if not content:
                print(f"    警告: 空正文 {item['title'][:30]}")
                total_skipped += 1
                continue
            
            c.execute(
                "INSERT OR IGNORE INTO gov_raw (title, page_url, content, publish_date, site_name) VALUES (?, ?, ?, ?, ?)",
                (item["title"], item["url"], content, pub, SITE_NAME)
            )
            if c.rowcount > 0:
                total_added += 1
            conn.commit()
        
        if cutoff_reached:
            break
    
    conn.close()
    print(f"完成: 新增 {total_added} 条, 跳过 {total_skipped} 条")

if __name__ == "__main__":
    crawl()
