#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
左权县人民政府 - 民意征集 (www.jzzq.gov.cn 注意: jzzq=晋中左权, 山西)
栏目: 政民互动 > 民意征集 /hdjl/zmyzj (26条/3页)
CMS: 开普云 kaipuyun (BBI JS反爬混淆, 需 ?LMCL=HcSri1 参数绕过)
列表: /hdjl/zmyzj (第1页) /hdjl/zmyzj_{page} (第2页起), 均需 ?LMCL=HcSri1
      ul.pageTPList > li > div.title > a.tit (href=/hdjl/zmyzj/content_{id}, title=完整标题)
      摘要 div.intro, 日期 span.date
详情: /hdjl/zmyzj/content_{id}?LMCL=HcSri1
      标题 h2.title, 日期 div.property "发布时间：YYYY-MM-DD", 正文 div.conTxt (含表格)
用法: python3 crawl_jzzq_zmyzj.py [--pages=N | N] [--sync] [--sync-only]
"""
import re
import sys
import os
import json
import time
import html as html_mod
import urllib.parse
import requests
import sqlite3
from concurrent.futures import ThreadPoolExecutor, as_completed

SITE_NAME = "左权县-民意征集"
BASE_URL = "http://www.jzzq.gov.cn"
LIST_TPL = "http://www.jzzq.gov.cn/hdjl/zmyzj{suffix}?LMCL=HcSri1"
LMCL = "?LMCL=HcSri1"
DOMAIN = "www.jzzq.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 = 5
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",
}


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


def fetch(url, retries=3):
    for i in range(retries):
        try:
            r = requests.get(url, headers=HEADERS, timeout=30, verify=False)
            r.encoding = "utf-8"
            if r.status_code == 200 and len(r.text) > 500:
                return r.text
        except Exception as e:
            if i < retries - 1:
                time.sleep(2)
    return None


def extract_list_items(html_text, base_url):
    items = []
    if not html_text:
        return items
    # li > div.title > a.tit (title 属性完整标题) + div.intro 摘要 + span.date
    for m in re.finditer(
        r'<li[^>]*>\s*<div class="title">\s*<a[^>]*href="(/hdjl/zmyzj/content_(\d+))"[^>]*title="([^"]*)"[^>]*>.*?</a>'
        r'.*?<div class="con">.*?<div class="intro">(.*?)</div>.*?<span class="date">([^<]*)</span>',
        html_text, re.DOTALL):
        href, iid, title, intro, date = m.group(1), m.group(2), m.group(3), m.group(4), m.group(5).strip()
        title = clean_title(title)
        if not title or len(title) < 4:
            continue
        items.append({
            "title": title,
            "url": base_url + href + LMCL,
            "pub_date": date.strip(),
            "id": iid,
            "intro": clean_title(re.sub(r"<[^>]+>", "", intro))[:200],
        })
    return items


def get_page_count(html_text):
    m = re.search(r"共(\d+)条信息/共(\d+)页", html_text or "")
    if m:
        return int(m.group(2))
    return 1


def parse_detail(url):
    html_text = fetch(url)
    if not html_text:
        return None

    title = ""
    m = re.search(r'<h2 class="title"[^>]*>(.*?)</h2>', html_text, re.DOTALL)
    if m:
        title = clean_title(re.sub(r"<[^>]+>", "", 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*民意征集.*$|_\s*政民互动.*$", "", m.group(1).strip()))

    pub_date = ""
    m = re.search(r'<div class="property"[^>]*>(.*?)</div>', html_text, re.DOTALL)
    if m:
        d = re.search(r"(\d{4})-(\d{2})-(\d{2})", m.group(1))
        if d:
            pub_date = d.group(0)
    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 class="conTxt"[^>]*>(.*?)</div>\s*(?:</div>)?', html_text, re.DOTALL)
    if m:
        body_html = m.group(1)
    if not body_html:
        m = re.search(r'<div class="conTxt"[^>]*>(.*)', html_text, re.DOTALL)
        if m:
            body_html = m.group(1)

    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)

    # 附件
    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 "/attach" in href.lower() or "/download" 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].split("?")[0], "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)

    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"[JZZQ-ZMYZJ] 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, 1000):
        if max_pages and pg > max_pages:
            break
        suffix = "" if pg == 1 else f"_{pg}"
        url = LIST_TPL.format(suffix=suffix)
        html_text = fetch(url)
        if not html_text:
            print(f"[list] P{pg} 获取失败")
            break
        if pg == 1:
            total_pages = get_page_count(html_text)
            print(f"[list] 总页数={total_pages}")
        items = extract_list_items(html_text, BASE_URL)
        print(f"[list] P{pg}: {len(items)} 条")
        if not items:
            break
        all_items.extend(items)
        if pg >= total_pages:
            break
    print(f"[total] 列表共 {len(all_items)} 条")

    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 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] or it.get("intro", ""),
                "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()
