#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
crawl_jianhu_hpgs.py - 建湖-项目环评
https://www.jianhu.gov.cn/col/col21201/index.html
列表: TRS dataproxy.jsp 动态接口 (CDATA 内 li > a[title] + span 日期)
  https://www.jianhu.gov.cn/module/web/jpage/dataproxy.jsp?page=N&appid=1&webid=57&path=/&columnid=21201&unitid=49858&webname=建湖县人民政府&permissiontype=0
详情: /art/YYYY/M/D/art_21201_ID.html
  → <!--$[标题名称(html)]>begin--> 标题 + sp_time "发布日期：YYYY-MM-DD" + #zoom 正文(含表格+附件downfile)
注意: 附件 href 是 /module/download/downfile.jsp?classid=0&filename=xxx 需转绝对 URL (&amp; 是合法HTML实体, 浏览器自动解码)
"""
import sys
import os
import re
import time
import html as html_lib
import urllib.parse
import sqlite3
import json

import requests
from bs4 import BeautifulSoup, Comment

# ---------------- config ----------------
BASE_URL = "https://www.jianhu.gov.cn"
LIST_URL = BASE_URL + "/module/web/jpage/dataproxy.jsp"
SITE_NAME = "建湖-项目环评"
GROUP_NAME = "江苏"
SCRIPT_NAME = "crawl_jianhu_hpgs.py"
DB_PATH = os.environ.get("DB_PATH", "/root/search.db")
JSONL_PATH = os.environ.get("JSONL_PATH", "")
ENC = "utf-8"

HEADERS = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.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",
}

REQUEST_INTERVAL = 1.5  # 统一节流
_last_req = 0.0

_MAX_PAGES = 1
for i, a in enumerate(sys.argv):
    if a.startswith("--pages="):
        try:
            _MAX_PAGES = int(a.split("=", 1)[1])
        except ValueError:
            pass
    elif a == "--pages" and i + 1 < len(sys.argv):
        try:
            _MAX_PAGES = int(sys.argv[i + 1])
        except ValueError:
            pass
_PAGES = _MAX_PAGES if _MAX_PAGES >= 1 else 1


def http_get(url, retries=3, timeout=30):
    global _last_req
    dt = time.time() - _last_req
    if dt < REQUEST_INTERVAL:
        time.sleep(REQUEST_INTERVAL - dt)
    _last_req = time.time()
    for i in range(retries):
        try:
            r = requests.get(url, headers=HEADERS, timeout=timeout, verify=False)
            if r.status_code == 200:
                r.encoding = "utf-8"
                return r
        except Exception:
            pass
        time.sleep(2 + i * 2)
    return None


def clean_title(t):
    if not t:
        return ""
    t = html_lib.unescape(t)
    t = t.replace("\u200b", "").replace("\u200c", "").replace("\u200d", "").replace("\ufeff", "")
    t = re.sub(r"\s+", " ", t)
    return t.strip()


def fetch_list(page):
    """调 dataproxy.jsp 拿一页列表, 返回 (总页数, 总条数, [(abs_url,title,date)])"""
    params = {
        "page": page,
        "appid": 1,
        "webid": 57,
        "path": "/",
        "columnid": 21201,
        "unitid": "49858",
        "webname": "建湖县人民政府",
        "permissiontype": 0,
    }
    r = http_get(LIST_URL + "?" + urllib.parse.urlencode(params))
    if r is None:
        return 0, 0, []
    html_text = r.text
    totalpage = 0
    totalrecord = 0
    tm = re.search(r"<totalpage>(\d+)</totalpage>", html_text)
    rm = re.search(r"<totalrecord>(\d+)</totalrecord>", html_text)
    if tm:
        totalpage = int(tm.group(1))
    if rm:
        totalrecord = int(rm.group(1))
    items = []
    for m in re.finditer(r"<record><!\[CDATA\[(.*?)\]\]></record>", html_text, re.S):
        block = m.group(1)
        hm = re.search(r'<a href="([^"]+)"[^>]*>(.*?)<span>(.*?)</span></a>', block, re.S)
        if not hm:
            continue
        href = hm.group(1)
        title = clean_title(re.sub(r"<[^>]+>", "", hm.group(2)))
        date = hm.group(3).strip()
        abs_url = urllib.parse.urljoin(BASE_URL, href)
        items.append((abs_url, title, date))
    return totalpage, totalrecord, items


def parse_detail(url):
    """详情页: 返回 (title, pubdate, zoom_soup)"""
    r = http_get(url)
    if r is None:
        return None, None, None
    html_text = r.text
    soup = BeautifulSoup(html_text, "html.parser")
    # 标题: <!--$[标题名称(html)]>begin-->...end 优先, fallback meta ArticleTitle
    tm = re.search(r"<!--<\$\[标题名称\(html\)\]>begin-->(.*?)<!--<\$\[标题名称\(html\)\]>end-->", html_text, re.S)
    if tm:
        title = clean_title(tm.group(1))
    else:
        tm2 = re.search(r'<meta name="ArticleTitle" content="([^"]*)"', html_text)
        title = clean_title(tm2.group(1)) if tm2 else ""
    dm = re.search(r"发布日期：(\d{4}-\d{2}-\d{2})", html_text)
    pubdate = dm.group(1) if dm else ""
    zoom = soup.find("div", id="zoom")
    if not zoom:
        return title, pubdate, None
    for c in zoom.find_all(string=lambda s: isinstance(s, Comment)):
        c.extract()
    return title, pubdate, zoom


def html_to_text(zoom_soup, abs_url):
    """正文: 保留表格/附件, 附件转绝对URL, 去脚本样式"""
    if zoom_soup is None:
        return "", False, []
    for tag in zoom_soup.find_all(["script", "style", "iframe", "object"]):
        tag.decompose()
    has_table = bool(zoom_soup.find("table"))
    attachments = []
    for a in zoom_soup.find_all("a", href=True):
        h = a["href"].strip()
        if h.startswith("/") or h.startswith("http"):
            a["href"] = urllib.parse.urljoin(BASE_URL, h)
        # 收集附件类链接
        if "downfile" in h or "download" in h:
            txt = clean_title(a.get_text())
            if txt:
                attachments.append((a["href"], txt))
    content = str(zoom_soup)
    return content, has_table, attachments


def append_attachments(content, attachments):
    if not attachments:
        return content
    parts = [content] if content.strip() else []
    for abs_url, txt in attachments:
        parts.append(f'<p><a href="{abs_url}" target="_blank">{txt}</a></p>')
    return "\n\n".join(parts)


def load_existing_urls(conn):
    try:
        cur = conn.execute("SELECT page_url FROM gov_raw WHERE site_name=?", (SITE_NAME,))
        return {row[0] for row in cur.fetchall()}
    except Exception:
        return set()


def store_record(conn, url, title, content, date, has_table):
    cur = conn.execute("SELECT id FROM gov_raw WHERE page_url=? AND site_name=?", (url, SITE_NAME))
    if cur.fetchone():
        return False
    try:
        industry = "other"
        try:
            from crawler_lib import classify_industry
            industry = classify_industry(title)
        except Exception:
            pass
        cur = conn.execute(
            "INSERT OR IGNORE INTO gov_raw "
            "(page_url, source_url, title, content, publish_date, site_name, group_name, script_name, has_table, industry) "
            "VALUES (?,?,?,?,?,?,?,?,?,?)",
            (url, url, title, content, date, SITE_NAME, GROUP_NAME, SCRIPT_NAME, has_table, industry),
        )
        if cur.rowcount > 0:
            summary = re.sub(r"<[^>]+>", "", content)
            summary = html_lib.unescape(summary)
            summary = re.sub(r"\s+", " ", summary).strip()[:200]
            conn.execute(
                "INSERT OR IGNORE INTO gov_search (rowid, title, site_name, summary) VALUES (?,?,?,?)",
                (cur.lastrowid, title, SITE_NAME, summary),
            )
            return True
        return False
    except sqlite3.OperationalError as e:
        if "locked" in str(e):
            time.sleep(3)
            return store_record(conn, url, title, content, date, has_table)
        raise


def main():
    conn = None
    if not JSONL_PATH:
        conn = sqlite3.connect(DB_PATH, timeout=60)
        conn.execute("PRAGMA busy_timeout=60000")
        conn.execute("PRAGMA journal_mode=WAL")
        existing = load_existing_urls(conn)
        print(f"已入库 {len(existing)} 条, 用于列表级预查重", flush=True)

    new_count = 0
    skip_count = 0
    jsonl_rows = []

    totalpage, totalrecord, _ = fetch_list(1)
    npages = min(_PAGES, totalpage) if totalpage else _PAGES
    print(f"[list] totalpage={totalpage} totalrecord={totalrecord} fetch_pages={npages}", flush=True)

    for page in range(1, npages + 1):
        tp, tr, items = fetch_list(page)
        print(f"[list] page={page} items={len(items)}", flush=True)
        if not items:
            print("Empty page, stop pagination", flush=True)
            break
        for abs_url, title, date in items:
            if not JSONL_PATH and abs_url in existing:
                skip_count += 1
                continue
            dtitle, ddate, zoom = parse_detail(abs_url)
            if zoom is None:
                print(f"  skip empty: {title[:30]}", flush=True)
                skip_count += 1
                continue
            if not dtitle:
                dtitle = title
            if not ddate:
                ddate = date
            content, has_table, atts = html_to_text(zoom, abs_url)
            content = append_attachments(content, atts)
            plain_len = len(re.sub(r"<[^>]+>", "", content).strip())
            if plain_len < 10:
                print(f"  skip empty: {dtitle[:30]}", flush=True)
                skip_count += 1
                continue
            if JSONL_PATH:
                jsonl_rows.append({
                    "page_url": abs_url, "title": dtitle, "content": content,
                    "publish_date": ddate, "has_table": has_table,
                    "site_name": SITE_NAME, "group_name": GROUP_NAME,
                    "script_name": SCRIPT_NAME,
                })
                print(f"  JSONL + {dtitle[:40]} ({ddate})", flush=True)
                new_count += 1
                continue
            ok = store_record(conn, abs_url, dtitle, content, ddate, has_table)
            if ok:
                new_count += 1
                existing.add(abs_url)
                print(f"  + {dtitle[:40]} ({ddate})", flush=True)
            else:
                skip_count += 1

    if JSONL_PATH:
        with open(JSONL_PATH, "w", encoding="utf-8") as f:
            for row in jsonl_rows:
                f.write(json.dumps(row, ensure_ascii=False) + "\n")
        print(f"JSONL written: {JSONL_PATH} ({len(jsonl_rows)} rows)", flush=True)

    if conn is not None:
        conn.commit()
        conn.close()
    print(f"[done] new={new_count} skip={skip_count}", flush=True)


if __name__ == "__main__":
    main()
