#!/usr/bin/env python3
import json
"""靖江市人民政府-项目审批公示 爬虫
JPAAS API: /api-gateway/jpaas-publish-server/front/page/build/unit
"""
import requests
import re
import os
import json
from bs4 import BeautifulSoup

SEARCH_DB = os.getenv("SEARCH_DB", "/root/search.db")
SITE_NAME = "靖江市-项目审批公示"
BASE_URL = "http://www.jingjiang.gov.cn"
API_URL = f"{BASE_URL}/api-gateway/jpaas-publish-server/front/page/build/unit"
API_PARAMS = {
    "parseType": "bulidstatic",
    "webId": "9e6365fd9072460da5320d31dc9f14a9",
    "tplSetId": "7cbe45ea58b84bcab5d12ba146aabfad",
    "pageType": "column",
    "tagId": "正文",
    "editType": "null",
    "pageId": "OvWQVZbk3X1JNPsL4Y0dX",
}
TOTAL_ROWS = 512
PAGE_SIZE = 15
TOTAL_PAGES = (TOTAL_ROWS + PAGE_SIZE - 1) // PAGE_SIZE  # 35

HEADERS = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36",
    "Referer": f"{BASE_URL}/xxgk/zdlyxxgk/sthj/xmspgs/index.html",
}


def fetch_api(page_no):
    """调用JPAAS API获取列表页数据（带paramJson分页）"""
    params = {**API_PARAMS}
    params["paramJson"] = json.dumps({"pageNo": page_no, "pageSize": PAGE_SIZE}, ensure_ascii=False)
    try:
        r = requests.get(API_URL, params=params, headers=HEADERS, timeout=30)
        r.encoding = "utf-8"
        data = r.json()
        if data.get("success") and data.get("data", {}).get("html"):
            return data["data"]["html"]
        return None
    except Exception as e:
        print(f"  ❌ API请求失败: {e}")
        return None


def fetch_detail(url):
    """获取详情页"""
    try:
        if not url.startswith("http"):
            url = BASE_URL + url
        r = requests.get(url, headers=HEADERS, timeout=30)
        r.encoding = "utf-8"
        return r.text
    except Exception as e:
        return None


def parse_list_from_html(html):
    """从API返回的HTML中解析列表项"""
    items = []
    soup = BeautifulSoup(html, "html.parser")
    ul = soup.find("ul", id="gz_list")
    if not ul:
        return items
    for li in ul.find_all("li", recursive=False):
        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
        detail_url = BASE_URL + href if href.startswith("/") else href

        # Date from <b class="fr">
        b = li.find("b", class_="fr")
        date_str = b.get_text(strip=True) if b 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="title">
    title = ""
    h1 = soup.find("h1", class_="title")
    if h1:
        title = h1.get_text(strip=True)

    # Date
    publish_date = ""
    sub_title = soup.find("div", class_="sub-title")
    if sub_title:
        text = sub_title.get_text()
        m = re.search(r'(\d{4}-\d{2}-\d{2})', text)
        if m:
            publish_date = m.group(1)
    if not publish_date:
        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)

    # Content from <div class="zoom">
    content = ""
    zoom_div = soup.find("div", class_="zoom")
    if zoom_div:
        content = str(zoom_div)

    return title, content, publish_date


def crawl():
    conn = None
    try:
        import sqlite3
        conn = sqlite3.connect(SEARCH_DB, timeout=60)
        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):
            html = fetch_api(page)
            if not html:
                print(f"第{page}/{TOTAL_PAGES}页: 无数据")
                continue

            items = parse_list_from_html(html)
            if not items:
                print(f"第{page}/{TOTAL_PAGES}页: 无数据，结束分页")
                break

            print(f"第{page}/{TOTAL_PAGES}页: {len(items)}条")

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

                detail_html = fetch_detail(detail_url)
                if not detail_html:
                    print(f"  [{i}/{len(items)}] ❌ 详情失败: {title[:30]}...")
                    continue

                _, content, publish_date = parse_detail(detail_html)
                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()
