#!/usr/bin/env python3
"""新星经济技术开发区管理委员会 - 行政执法公示"""
import os, sys, re, requests
from bs4 import BeautifulSoup
from datetime import datetime, timedelta

BASE_URL = "https://www.btnsss.gov.cn"
LIST_URL = BASE_URL + "/info/iList.jsp?cat_id=11974&BigCat_id=11974"
PAGE_URL_TPL = BASE_URL + "/info/iList.jsp?cat_id=11974&cur_page={}"
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 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36",
    "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
    "Accept-Language": "zh-CN,zh;q=0.9"
}

import urllib3
urllib3.disable_warnings()

def get_page_count():
    """获取总页数"""
    try:
        r = requests.get(LIST_URL, 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))
        return 1
    except Exception as e:
        print(f"[ERROR] get page count: {e}", file=sys.stderr)
        return 1

def parse_list(html):
    """解析列表页"""
    soup = BeautifulSoup(html, "html.parser")
    items = []
    for li in soup.select("ul.gk-nr-ul li"):
        a = li.find("a", class_="gk-br")
        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)[:10]
        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 = ""
        nr = soup.select_one("div.con-nr")
        if nr:
            content = str(nr)
        # source
        source = ""
        src_m = re.search(r'来源[：:]\s*([^<]+)', r.text)
        if src_m:
            source = src_m.group(1).strip()
        return content, source
    except Exception as e:
        print(f"  [ERROR] detail: {e}", file=sys.stderr)
        return "", ""

def store_item(title, url, date, content, source):
    """写入search.db"""
    import sqlite3
    try:
        conn = sqlite3.connect(DB_PATH)
        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: {e}", file=sys.stderr)
        return False

def main():
    page_count = get_page_count()
    print(f"总页数: {page_count}")

    new_count = 0
    skip_count = 0

    for page in range(1, page_count + 1):
        url = PAGE_URL_TPL.format(page) if page > 1 else LIST_URL
        print(f"\n--- 第{page}页 ---")
        try:
            r = requests.get(url, headers=HEADERS, timeout=30, verify=False)
            r.encoding = "utf-8"
            items = parse_list(r.text)
        except Exception as e:
            print(f"  [ERROR] list page {page}: {e}")
            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}, 跳过: {skip_count}")

if __name__ == "__main__":
    main()
