#!/usr/bin/env python3
"""池州市生态环境局 - 环境影响评价公众参与"""
import os, sys, re, time, json
import requests
from bs4 import BeautifulSoup
from datetime import datetime, timedelta

BASE_URL = "https://sthjj.chizhou.gov.cn"
COLUMN_ID = "5578"
LIST_URL = f"{BASE_URL}/Content/showList/{COLUMN_ID}/page_{{}}.html"
SITE_NAME = "池州市生态环境局"
DATE_THRESHOLD = (datetime.now() - timedelta(days=365*3)).strftime("%Y-%m-%d")

DB_PATH = os.getenv("SEARCH_DB", "/root/search.db")

HEADERS = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36"
}

def get_total_pages():
    """获取总页数"""
    try:
        r = requests.get(LIST_URL.format(1), headers=HEADERS, timeout=30, verify=False)
        r.encoding = "utf-8"
        m = re.search(r'pagecount="(\d+)"', r.text)
        if m:
            return int(m.group(1))
        # fallback: also check total
        m2 = re.search(r'total="(\d+)"', r.text)
        if m2:
            total = int(m2.group(1))
            return (total + 14) // 15
        return 1
    except:
        return 1

def parse_list_page(html):
    """解析列表页"""
    soup = BeautifulSoup(html, "html.parser")
    items = []
    for li in soup.select("div.m-cglist ul li"):
        a = li.find("a")
        span = li.find("span")
        if not a or not span:
            continue
        href = a.get("href", "")
        title = a.get("title", "") or a.get_text(strip=True)
        date = span.get_text(strip=True)
        if not href.startswith("http"):
            href = BASE_URL + href
        items.append({"title": title, "url": href, "date": date})
    return items

def fetch_detail(url):
    """获取详情页内容"""
    try:
        r = requests.get(url, headers=HEADERS, timeout=30, verify=False)
        r.encoding = "utf-8"
        soup = BeautifulSoup(r.text, "html.parser")

        # 正文
        content_div = soup.select_one("div#zoom")
        content = ""
        if content_div:
            content = str(content_div)

        # 来源
        source = ""
        meta_source = soup.find("meta", attrs={"name": "ContentSource"})
        if meta_source:
            source = meta_source.get("content", "")
        if not source:
            src_span = soup.select_one(".u-wzinfo span")
            if src_span:
                t = src_span.get_text(strip=True)
                if "来源" in t:
                    source = t.replace("来源：", "").strip()

        return content, source
    except Exception as e:
        print(f"  [ERROR] fetch detail failed: {e}", file=sys.stderr)
        return "", ""

def store_item(title, url, date, content, source):
    """写入search.db"""
    import sqlite3
    try:
        conn = sqlite3.connect(DB_PATH, timeout=60)
        c = conn.cursor()
        c.execute("""
            INSERT OR IGNORE INTO gov_raw (title, page_url, publish_date, content, site_name)
            VALUES (?, ?, ?, ?, ?)
        """, (title.strip(), url.strip(), date, content, SITE_NAME))
        affected = c.rowcount
        conn.commit()
        conn.close()
        return affected > 0
    except Exception as e:
        print(f"  [ERROR] store failed: {e}", file=sys.stderr)
        return False

def main():
    import urllib3
    urllib3.disable_warnings()

    total_pages = get_total_pages()
    print(f"总页数: {total_pages}")

    new_count = 0
    skip_count = 0
    error_count = 0

    for page in range(1, total_pages + 1):
        print(f"\n--- 第{page}页 ---")
        try:
            r = requests.get(LIST_URL.format(page), headers=HEADERS, timeout=30, verify=False)
            r.encoding = "utf-8"
            items = parse_list_page(r.text)
        except Exception as e:
            print(f"  [ERROR] list page {page}: {e}")
            error_count += 1
            continue

        for item in items:
            # 日期过滤
            if item["date"] < DATE_THRESHOLD:
                skip_count += 1
                continue

            print(f"  {item['date']} {item['title'][:50]}...")

            # 获取详情
            content, source = fetch_detail(item["url"])

            if store_item(item["title"], item["url"], item["date"], content, source):
                new_count += 1
                print(f"    ✓ 新增")
            else:
                skip_count += 1
                print(f"    - 已存在")

    print(f"\n\n=== 完成 ===")
    print(f"新增: {new_count}")
    print(f"跳过: {skip_count}")
    print(f"错误: {error_count}")

if __name__ == "__main__":
    main()
