#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
昌邑市人民政府 - 业务信息 (changyi.gov.cn/CYSXXGK/ZTZL/fdzdgkall.html -> 业务信息栏目)
CMS: 潍坊市政府信息公开平台 (ELS/SYS-service API)
栏目树: GET  http://www.changyi.gov.cn/sys-service/webcata/catas/108  (业务信息 cataid=4216, 6221条)
列表:   POST http://www.changyi.gov.cn/els-service/article/{page}/13
        body {"catas":["4216"],"dq":"108"}  → data.contents[]: subject/fwdate/url/dwname
详情:   /CYSXXGK/.../t{date}_{xxid}.htm  正文 div#ivs_content, meta ArticleTitle/PubDate
用法: python3 crawl_changyi_ywxx.py [--pages=N | N] [--sync] [--sync-only]
"""
import re
import sys
import os
import json
import html as html_mod
import requests
import sqlite3
from concurrent.futures import ThreadPoolExecutor, as_completed

SITE_NAME = "昌邑市人民政府-业务信息"
BASE_URL = "http://www.changyi.gov.cn"
CATAS_API = "http://www.changyi.gov.cn/sys-service/webcata/catas/108"
LIST_API = "http://www.changyi.gov.cn/els-service/article/{page}/13"
CATA_ID = "4216"  # 业务信息
DQ = "108"
DOMAIN = "www.changyi.gov.cn"
GROUP = "山东"
CUTOFF = "2020-01-01"
DB_PATH = os.environ.get("DB_PATH", "/root/search.db")
QUALITY_DB = os.path.join(os.path.dirname(os.path.abspath(__file__)), "quality_results.db")
MAX_WORKERS = 6
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",
    "Content-Type": "application/json;charset=UTF-8",
}


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 fetch_list(page):
    """POST 获取列表页，返回 (items, total_pages)"""
    try:
        r = requests.post(LIST_API.format(page=page), headers=HEADERS,
                          data=json.dumps({"catas": [CATA_ID], "dq": DQ}), 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 [], 0
        d = j.get("data", {})
        total_pages = int(d.get("totalPages") or 0)
        items = []
        for c in d.get("contents") or []:
            subject = clean_title(c.get("subject") or "")
            url = (c.get("url") or "").strip()
            fwdate = (c.get("fwdate") or "").strip()[:10]
            if not subject or not url:
                continue
            items.append({
                "title": subject,
                "url": url,
                "pub_date": fwdate,
                "dwname": (c.get("dwname") or "").strip(),
            })
        return items, total_pages
    except Exception as e:
        print(f"  [list] P{page} ERR: {e}")
        return [], 0


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

    title = ""
    m = re.search(r'<meta\s+name="ArticleTitle"\s+content="([^"]*)"', html_text)
    if m:
        title = clean_title(m.group(1))
    if not title:
        m = re.search(r"<title>(.*?)</title>", html_text, re.DOTALL)
        if m:
            title = clean_title(re.sub(r"^\S+--", "", m.group(1).strip()))
            title = re.sub(r"[-_—]\s*.*$", "", title).strip()

    pub_date = ""
    m = re.search(r'<meta\s+name="PubDate"\s+content="([^"]*)"', html_text)
    if m:
        pub_date = m.group(1).strip()[:10]
    if not pub_date:
        m = re.search(r"(\d{4})-(\d{2})-(\d{2})", html_text)
        if m:
            pub_date = m.group(0)

    body_html = ""
    m = re.search(r'<div[^>]*id="ivs_content"[^>]*>(.*?)</div>\s*(?:</div>)?', html_text, re.DOTALL)
    if m:
        body_html = m.group(1)
    else:
        m = re.search(r'<div[^>]*class="Article_content[^"]*"[^>]*>(.*?)</div>\s*(?:</div>)?', html_text, re.DOTALL)
        if m:
            body_html = m.group(1)
    if not body_html:
        # 兜底: 整个内容区
        m = re.search(r'<div[^>]*id="ContentRegion2"[^>]*>(.*?)</div>', html_text, re.DOTALL)
        if m:
            body_html = m.group(1)

    # 去掉 TRS 样式块
    body_html = re.sub(r"<style[^>]*>.*?</style>", "", body_html, flags=re.S | re.I)
    body_html = re.sub(r"<script[^>]*>.*?</script>", "", body_html, flags=re.S | re.I)

    # 附件：正文内链接
    atts = []
    for m in re.finditer(r'<a[^>]*href="([^"]+)"[^>]*>([^<]{0,120})</a>', body_html):
        href, name = m.group(1).strip(), clean_title(m.group(2))
        if re.search(r"\.(pdf|doc|docx|xls|xlsx|zip|rar|wps|7z|et|dps)$", href, re.I) or "/download" in href.lower() or "/attach" in href.lower():
            abs_url = href if href.startswith("http") else (href if href.startswith("//") else BASE_URL + (href if href.startswith("/") else "/" + href))
            if not any(a["url"] == abs_url for a in atts):
                atts.append({"name": name or href.split("/")[-1], "url": abs_url})

    # 绝对化链接
    def abs_link(m):
        href = m.group(1).strip()
        if href.startswith("http") or href.startswith("javascript") or href.startswith("#"):
            return m.group(0)
        if href.startswith("//"):
            return m.group(0).replace(href, "http:" + href)
        return m.group(0).replace(href, BASE_URL + href if href.startswith("/") else BASE_URL + "/" + href)

    body_html = re.sub(r'href="([^"]+)"', abs_link, body_html)
    body_html = re.sub(r'src="([^"]+)"', abs_link, body_html)
    body_html = re.sub(r"<p[^>]*>", "<p>", body_html)
    body_html = re.sub(r"<p>\s*</p>", "", body_html)

    # 清理分享/二维码/打印
    body_html = re.sub(r'<div[^>]*class="[^"]*(share|ewm|qrcode|print|bshare)[^"]*"[^>]*>.*?</div>', "", body_html, flags=re.S | re.I)
    body_html = re.sub(r'<div[^>]*class="[^"]*(article|content)[^"]*"[^>]*>\s*</div>', "", body_html, flags=re.S | re.I)

    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": []}
    return {"title": title, "content": body_html, "pub_date": pub_date, "attachments": atts}


def push_local(records, script_name):
    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_local] new={n_new} skip={len(records)-n_new}")
    return n_new


def sync_to_server():
    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(DB_PATH, 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 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 main():
    sync_only = "--sync-only" in sys.argv
    max_pages = None
    do_sync = "--sync" in sys.argv
    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"[ChangyiYW] max_pages={max_pages} sync_only={sync_only}")
    if sync_only:
        sync_to_server()
        return

    all_items = []
    total_pages = 0
    for pg in range(1, 10000):
        if max_pages and pg > max_pages:
            break
        items, tpages = fetch_list(pg)
        if tpages:
            total_pages = tpages
        print(f"[list] P{pg}: items={len(items)} (totalPages={tpages})")
        if not items:
            break
        all_items.extend(items)
        if pg >= tpages:
            break
    print(f"[total] 列表共 {len(all_items)} 条 (totalPages={total_pages})")

    valid = []
    with ThreadPoolExecutor(max_workers=MAX_WORKERS) as executor:
        fut_map = {executor.submit(parse_detail, it["url"]): it for it in all_items}
        done = 0
        for fut in as_completed(fut_map):
            it = fut_map[fut]
            det = fut.result()
            done += 1
            if done % 50 == 0:
                print(f"  详情 {done}/{len(all_items)}...", flush=True)
            if det is None:
                print(f"  [fail] {it['title'][:40]}")
                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": GROUP,
                "script_name": os.path.basename(sys.argv[0]),
                "attachments": json.dumps(det["attachments"], ensure_ascii=False) if det["attachments"] else "[]",
            }
            valid.append(rec)
    print(f"[total] valid={len(valid)}")
    if valid:
        push_local(valid, os.path.basename(sys.argv[0]))
        if do_sync:
            sync_to_server()


if __name__ == "__main__":
    main()
