#!/usr/bin/env python3
"""象山县-建设项目环境影响评价信息公示 爬虫 (Hanweb JPAAS)"""
import re, sys, os, time, json
import requests
from bs4 import BeautifulSoup
from urllib.parse import quote

API_BASE = "https://www.xiangshan.gov.cn/api-gateway/jpaas-publish-server/front/page/build/unit"
BASE_URL = "https://www.xiangshan.gov.cn"
DB_PATH = "/root/search.db"
SITE_NAME = "象山县-环评公示"
TABLE_NAME = "gov_raw"
MAX_PAGES = 5  # 实际只有2页

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",
    "Referer": "https://www.xiangshan.gov.cn/col/col1229858886/index.html",
}


def get_list_data(page):
    """调用JPAAS API获取列表数据"""
    params = {
        "parseType": "bulidstatic",
        "webId": "3507",
        "tplSetId": "ajlqS8KBSlYJbvZjmaHaS",
        "pageType": "column",
        "tagId": "信息list",
        "editType": "null",
        "pageId": "1229858886",
    }
    if page > 1:
        params["pageNo"] = str(page)

    try:
        r = requests.get(API_BASE, params=params, headers=HEADERS, timeout=30, verify=False)
        if r.status_code == 200:
            return r.json()
    except Exception as e:
        print(f"  [!] API请求失败: {e}", flush=True)
    return None


def parse_list(api_data):
    """从API返回的HTML中解析列表"""
    if not api_data or not api_data.get("success"):
        return []
    html = api_data.get("data", {}).get("html", "")
    if not html:
        return []

    soup = BeautifulSoup(html, "html.parser")
    items = []
    for li in soup.select("li"):
        a = li.select_one("a")
        if not a:
            continue
        href = a.get("href", "").strip()
        title = a.get("title", "").strip() or a.get_text(strip=True)
        date_span = li.select_one("span")
        date_str = date_span.get_text(strip=True) if date_span else ""

        if href and title:
            if href.startswith("http"):
                full_url = href
            else:
                full_url = BASE_URL + href
            items.append((title, full_url, date_str))
    return items


def fetch_detail(url):
    try:
        r = requests.get(url, headers=HEADERS, timeout=30, verify=False)
        if r.status_code != 200:
            return None, None, None
    except:
        return None, None, None

    soup = BeautifulSoup(r.text, "html.parser")

    # 标题
    title_el = soup.select_one("div.article h1")
    title = title_el.get_text(strip=True) if title_el else ""

    # 日期 - 从 article-top 中找 成文日期
    pub_date = ""
    for flex_div in soup.select("div.article-top div.flex"):
        h1 = flex_div.select_one("h1")
        p = flex_div.select_one("p")
        if h1 and p and "日期" in h1.get_text():
            txt = p.get_text(strip=True)
            m = re.search(r'(\d{4}-\d{2}-\d{2})', txt)
            if m:
                pub_date = m.group(1)

    # 正文 - div.article 中除了h1之外的内容
    article = soup.select_one("div.article")
    content = ""
    if article:
        # 复制article的内容，去掉h1
        content_parts = []
        for child in article.children:
            if child.name and child.name != 'h1':
                content_parts.append(str(child))
        content = "".join(content_parts)

    return title, pub_date, content


def main():
    requests.packages.urllib3.disable_warnings()

    import sqlite3
    conn = sqlite3.connect(DB_PATH)
    cur = conn.cursor()

    cur.execute(f"SELECT page_url FROM {TABLE_NAME}")
    existing_urls = set(row[0] for row in cur.fetchall())

    all_items = []
    for page in range(1, MAX_PAGES + 1):
        print(f"[*] 正在获取第{page}页...", flush=True)
        data = get_list_data(page)
        if not data:
            print(f"  [!] 第{page}页API无响应，跳过", flush=True)
            continue
        items = parse_list(data)
        print(f"  [→] 解析到 {len(items)} 条", flush=True)
        if not items:
            break
        all_items.extend(items)
        time.sleep(0.5)

    print(f"\n[*] 总计获取列表 {len(all_items)} 条", flush=True)

    new_items = [(t, u, d) for t, u, d in all_items if u not in existing_urls]
    print(f"[*] 排除已存在后，新增 {len(new_items)} 条", flush=True)

    if not new_items:
        print("[✓] 无新数据需要爬取", flush=True)
        conn.close()
        return

    inserted = 0
    for i, (title, url, date_str) in enumerate(new_items, 1):
        print(f"  [{i}/{len(new_items)}] {title[:40]}...", flush=True)
        det_title, det_date, content = fetch_detail(url)

        final_title = det_title or title
        final_date = det_date or date_str

        if not content or len(content.strip()) < 50:
            print(f"    [!] 内容为空或过短，跳过", flush=True)
            continue

        text_only = BeautifulSoup(content, "html.parser").get_text(strip=True)
        summary = text_only[:200] if text_only else ""

        try:
            cur.execute(
                f"INSERT OR IGNORE INTO {TABLE_NAME} (title, page_url, content, summary, publish_date, site_name) VALUES (?, ?, ?, ?, ?, ?)",
                (final_title, url, content, summary, final_date, SITE_NAME)
            )
            if cur.rowcount > 0:
                inserted += 1
                conn.commit()
        except Exception as e:
            print(f"    [!] 入库失败: {e}", flush=True)

        time.sleep(0.3)

    conn.close()
    print(f"\n[✓] 完成！入库 {inserted} 条新数据", flush=True)


if __name__ == "__main__":
    main()
