#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
温州瓯江口(海洋经济发展示范区) - 建设项目环境影响评价信息公示 (ojk.wenzhou.gov.cn/col/col1229874415/index.html)
CMS: 浙江政务 JCMS (ZJSJYH 单元构建) - 与新昌/洞头同款
列表: GET /api-gateway/jpaas-publish-server/front/page/build/unit
      params: parseType=bulidstatic&webId=2070&tplSetId=fbSBcd1C5fiSI7LwwVOpW&pageType=column
              &tagId=内页分页列表&editType=null&pageId=1229874415
              &paramJson={"pageNo":N,"pageSize":20,"search":""}
      响应 JSON data.html: <a href="/col/col.../art/...">标题</a>
      count=131 总条数 -> 7页 (20条/页)
详情: /col/col1229874415/art/YYYY/art_hex.html
      正文 div.zwnr_con > div#zoom > p
      meta PubDate / 时间：YYYY-MM-DD HH:MM
样本: https://ojk.wenzhou.gov.cn/col/col1229874415/art/2026/art_e85b48cb6178421491d45cbc10041d87.html
用法: python3 crawl_ojk_hpgs.py [--pages=N | N] [--sync-only]
"""
import requests
import re
import sys
import os
import json
import html as html_mod
from bs4 import BeautifulSoup, Tag

SITE_NAME = "温州瓯江口-建设项目环评公示"
BASE_URL = "https://ojk.wenzhou.gov.cn"
API_URL = "https://ojk.wenzhou.gov.cn/api-gateway/jpaas-publish-server/front/page/build/unit"
PAGE_ID = "1229874415"
TAG_ID = "内页分页列表"
TPL_SET = "fbSBcd1C5fiSI7LwwVOpW"
WEB_ID = "2070"
PAGE_SIZE = 20
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": f"https://ojk.wenzhou.gov.cn/col/col{PAGE_ID}/index.html",
}
CUTOFF = "2023-01-01"

QUALITY_DB = os.path.join(os.path.dirname(os.path.abspath(__file__)), "quality_results.db")
SEARCH_DB = "/root/search.db"
DOMAIN = "ojk.wenzhou.gov.cn"


def push_to_searchdb(records, batch_label):
    import sqlite3
    conn = sqlite3.connect(QUALITY_DB, timeout=60)
    conn.execute("PRAGMA busy_timeout=300000")
    cur = conn.cursor()
    cur.execute("""CREATE TABLE IF NOT EXISTS crawl_results (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        site_id INTEGER DEFAULT 0,
        title TEXT, url TEXT, content TEXT,
        publish_date TEXT, summary TEXT,
        domain TEXT, category TEXT DEFAULT '',
        content_hash TEXT, crawl_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        industry TEXT DEFAULT '', group_name TEXT DEFAULT '',
        script_name TEXT DEFAULT '', attachments TEXT DEFAULT '[]',
        UNIQUE(domain, url)
    )""")
    n_new = 0
    for r in records:
        try:
            cur.execute(
                "INSERT OR IGNORE INTO crawl_results (domain, title, url, content, publish_date, summary, industry, group_name, script_name, attachments) VALUES (?,?,?,?,?,?,?,?,?,?)",
                (r.get("domain", ""), r.get("title", ""), r.get("url", ""),
                 r.get("content", ""), r.get("pub_date", ""), r.get("summary", ""),
                 r.get("industry", ""), r.get("group_name", ""),
                 r.get("script_name", ""), r.get("attachments", "[]")),
            )
            n_new += cur.rowcount
        except Exception as e:
            print(f"  [push] ERR {r.get('url','')}: {e}")
    conn.commit()
    conn.close()
    print(f"[push_to_searchdb] new={n_new} skip={len(records)-n_new}")
    return n_new


def sync_to_server():
    import sqlite3
    try:
        conn = sqlite3.connect(QUALITY_DB, timeout=60)
        conn.execute("PRAGMA busy_timeout=300000")
        rows = conn.execute(
            "SELECT title, url, content, publish_date, summary, industry, group_name, script_name, attachments FROM crawl_results WHERE domain=? ORDER BY id",
            (DOMAIN,),
        ).fetchall()
        conn.close()
    except Exception as e:
        print(f"[sync] local read ERR: {e}")
        return
    if not rows:
        print("[sync] 本地没有数据")
        return
    dst = sqlite3.connect(SEARCH_DB, timeout=300)
    dst.execute("PRAGMA journal_mode=WAL")
    dst.execute("PRAGMA busy_timeout=300000")
    upd = ins = 0
    try:
        for r in rows:
            title, url, content, pub_date, summary, ind, grp, sn, att = r
            cur = dst.execute("SELECT id FROM gov_raw WHERE page_url=?", (url,))
            row = cur.fetchone()
            try:
                if row:
                    dst.execute(
                        "UPDATE gov_raw SET title=?, content=?, publish_date=?, summary=?, industry=?, group_name=?, script_name=?, attachments=? WHERE id=?",
                        (title, (content or "")[:500000], pub_date or "", (summary or "")[:300],
                         ind or "", grp or "", sn or "", att or "[]", row[0]))
                    upd += 1
                else:
                    dst.execute(
                        "INSERT INTO gov_raw (title, page_url, content, publish_date, summary, industry, group_name, script_name, attachments, site_name, source_url) VALUES (?,?,?,?,?,?,?,?,?,?,?)",
                        (title, url, (content or "")[:500000], pub_date or "", (summary or "")[:300],
                         ind or "", grp or "", sn or "", att or "[]", SITE_NAME, url))
                    ins += 1
            except Exception as e:
                print(f"  [sync] ERR {url}: {e}")
        dst.commit()
        dst.execute(
            "INSERT OR REPLACE INTO gov_search(rowid,title,site_name,summary) "
            "SELECT r.id,r.title,r.site_name,r.summary FROM gov_raw r "
            "WHERE r.id NOT IN (SELECT rowid FROM gov_search) AND r.site_name=?",
            (SITE_NAME,))
        dst.commit()
        total = dst.execute("SELECT COUNT(*) FROM gov_raw WHERE site_name=?", (SITE_NAME,)).fetchone()[0]
    finally:
        dst.close()
    print(f"[sync] OK updated={upd} inserted={ins} DB共{total}条")


def clean_title(t):
    t = re.sub(r"&middot;|&nbsp;|&#160;|\u200b|\ufeff", "", t or "")
    t = re.sub(r"^[•·]\s*", "", t)
    return re.sub(r"\s+", " ", t).strip()


def normalize_date(s):
    m = re.search(r"(\d{4})[年\-/.](\d{1,2})[月\-/.](\d{1,2})", s or "")
    if m:
        y, mo, d = int(m.group(1)), int(m.group(2)), int(m.group(3))
        return f"{y:04d}-{mo:02d}-{d:02d}"
    m = re.search(r"(\d{4})-(\d{2})-(\d{2})", s or "")
    if m:
        return m.group(0)
    return ""


def fetch_list(page):
    param_json = json.dumps({"pageNo": page, "pageSize": PAGE_SIZE, "search": ""}, ensure_ascii=False)
    params = {
        "parseType": "bulidstatic",
        "webId": WEB_ID,
        "tplSetId": TPL_SET,
        "pageType": "column",
        "tagId": TAG_ID,
        "editType": "null",
        "pageId": PAGE_ID,
        "paramJson": param_json,
    }
    try:
        r = requests.get(API_URL, params=params, headers=HEADERS, timeout=30)
        r.raise_for_status()
        j = r.json()
        if not j.get("success"):
            print(f"  [list] P{page} API fail: {j.get('message')}")
            return [], False, 0
        html = j["data"]["html"]
    except Exception as e:
        print(f"  [list] P{page} ERR: {e}")
        return [], False, 0
    items = []
    count = 0
    m = re.search(r'count="(\d+)"', html)
    if m:
        count = int(m.group(1))
    soup = BeautifulSoup(html, "html.parser")
    for a in soup.find_all("a", href=True):
        href = a["href"].strip()
        if "/art/" not in href:
            continue
        if not re.search(r"/art/\d{4}/art_[0-9a-f]+\.html$", href):
            continue
        title = clean_title(a.get_text(strip=True))
        if not title:
            continue
        full_url = href if href.startswith("http") else BASE_URL + (href if href.startswith("/") else "/" + href)
        items.append({"title": title, "url": full_url, "pub_date": ""})
    seen = set()
    uniq = []
    for it in items:
        if it["url"] in seen:
            continue
        seen.add(it["url"])
        uniq.append(it)
    return uniq, True, count


def parse_detail(url):
    try:
        r = requests.get(url, headers=HEADERS, timeout=30)
        r.raise_for_status()
        r.encoding = "utf-8"
        soup = BeautifulSoup(r.text, "html.parser")
    except Exception as e:
        print(f"  [detail] {url} ERR: {e}")
        return None

    title = ""
    m = re.search(r"<title>(.*?)</title>", r.text, re.S)
    if m:
        title = clean_title(re.sub(r"[-_—]\s*.*$", "", m.group(1).strip()))
    if not title:
        h = soup.find("h1")
        if h:
            title = clean_title(h.get_text())
    if not title:
        mt = soup.find("meta", attrs={"name": "ArticleTitle"})
        if mt and mt.get("content"):
            title = clean_title(mt["content"])

    pub_date = ""
    m = soup.find("meta", attrs={"name": "PubDate"})
    if m and m.get("content"):
        pub_date = m["content"].strip()[:10]
    if not pub_date:
        m = re.search(r"(?:时间|发布日期|发布时间)[：:]\s*(\d{4}-\d{2}-\d{2})", r.text)
        if m:
            pub_date = m.group(1)

    body_el = soup.select_one("div.zwnr_con") or soup.select_one("div#zoom") or soup.select_one("div.ny-content")
    if body_el is None:
        for el in soup.find_all(class_=re.compile("zwnr_con|ny-content|article-content|TRS_UEDITOR")):
            body_el = el
            break
    if body_el is None:
        return {"title": title, "content": "", "pub_date": pub_date, "attachments": []}

    # 附件（只处理正常 Tag，防 None/已解构元素）
    atts = []
    att_links = []
    for a in body_el.find_all("a"):
        if not isinstance(a, Tag):
            continue
        href = (a.get("href") or "").strip()
        if re.search(r"\.(pdf|doc|docx|xls|xlsx|zip|rar|wps|7z)$", href, re.I) or "/document/download" in href or "/attachment/" in href:
            abs_url = href if href.startswith("http") else ("https:" + href if href.startswith("//") else BASE_URL + (href if href.startswith("/") else "/" + href))
            name = clean_title(a.get_text(strip=True)) or a.get("download") or href.split("/")[-1]
            if not any(x["url"] == abs_url for x in atts):
                atts.append({"name": name, "url": abs_url})
            att_links.append(a)

    # 附件段落从正文移除（保留表格）— 先收集再删除
    for a in att_links:
        p = a.find_parent("p")
        if p:
            p.decompose()
    # 绝对化链接
    for a in body_el.find_all("a", href=True):
        href = a["href"].strip()
        if href.startswith("/") or href.startswith("./") or (not href.startswith("http") and not href.startswith("javascript")):
            a["href"] = ("https:" + href if href.startswith("//") else BASE_URL + (href if href.startswith("/") else "/" + href))
    for img in body_el.find_all("img"):
        src = img.get("src", "")
        if src and not src.startswith("http"):
            img["src"] = ("https:" + src if src.startswith("//") else BASE_URL + (src if src.startswith("/") else "/" + src))
    # 二维码/分享/打印清理
    for el in body_el.select("div.share, div.ewm, div.qrcode, div.jzgov-qrcode-div, div.app-share, div.print, div.bshare-custom, div.fzxxzs"):
        el.decompose()
    for el in body_el.find_all(string=re.compile("扫一扫|分享到|打印本页")):
        p = el.find_parent("p") or el.find_parent("div")
        if p:
            p.decompose()

    body_html = str(body_el.decode_contents())
    body_html = re.sub(r"<script[^>]*>.*?</script>", "", body_html, flags=re.S | re.I)
    body_html = re.sub(r"<style[^>]*>.*?</style>", "", body_html, flags=re.S | re.I)
    body_html = re.sub(r"<p[^>]*>", "<p>", body_html)
    body_html = re.sub(r"<p>\s*</p>", "", body_html)
    body_html = re.sub(r"\s*<div id=\"docAppendix\".*$", "", body_html, flags=re.S)
    body_html = re.sub(r"\s*<div class=\"video\".*$", "", body_html, flags=re.S)

    if atts:
        has_att = any(a["url"] in body_html for a in atts)
        if not has_att:
            att_html = "".join(f'<p><a href="{a["url"]}">{html_mod.escape(a["name"])}</a></p>' for a in atts)
            body_html = body_html.rstrip() + "\n" + att_html

    text_len = len(re.sub(r"<[^>]+>", "", body_html).strip())
    has_img = "<img" in body_html
    has_video = "<iframe" in body_html or "video" in body_html
    if text_len < 5 and not has_img and not has_video and not atts:
        return {"title": title, "content": "", "pub_date": pub_date, "attachments": atts}
    return {"title": title, "content": body_html, "pub_date": pub_date, "attachments": atts}


def main():
    sync_only = "--sync-only" in sys.argv
    max_pages = None
    for a in sys.argv[1:]:
        if a.startswith("--pages="):
            try:
                max_pages = int(a.split("=", 1)[1])
            except ValueError:
                pass
        elif a.isdigit():
            max_pages = int(a)
    print(f"[AutoPg] max_pages={max_pages} sync_only={sync_only}")
    if sync_only:
        sync_to_server()
        return

    valid = []
    total_count = 0
    for pg in range(1, 2000):
        if max_pages and pg > max_pages:
            break
        items, has_next, count = fetch_list(pg)
        if count:
            total_count = count
        print(f"[list] P{pg}: items={len(items)} (count={count})")
        if not items:
            break
        for it in items:
            det = parse_detail(it["url"])
            if det is None:
                print(f"  [fail] {it['title'][:50]}")
                det = {"title": it["title"], "content": "", "pub_date": it["pub_date"], "attachments": []}
            if det["pub_date"] and det["pub_date"] < CUTOFF:
                print(f"  [cutoff] {det['pub_date']} {det['title'][:40]}")
                continue
            rec = {
                "domain": DOMAIN,
                "site_name": SITE_NAME,
                "title": det["title"] or it["title"],
                "url": it["url"],
                "content": det["content"],
                "pub_date": det["pub_date"] or it["pub_date"],
                "summary": re.sub(r"<[^>]+>", "", det["content"])[:200],
                "industry": "",
                "group_name": "浙江",
                "script_name": os.path.basename(sys.argv[0]),
                "attachments": json.dumps(det["attachments"], ensure_ascii=False) if det["attachments"] else "[]",
            }
            valid.append(rec)
        if not has_next:
            break
    print(f"[total] valid={len(valid)} (count={total_count})")
    if valid:
        push_to_searchdb(valid, os.path.basename(sys.argv[0]))
        if "--sync" in sys.argv:
            sync_to_server()


if __name__ == "__main__":
    main()
