#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
九江经开区 - 通知公告
站点: jkq.jiujiang.gov.cn/zwzx_303/tzgg/
CMS: TRS 江西 (createPageHTML 分页 index_N.shtml)
列表: a[title=完整标题] href=./202608/t20260811_7290524.html
详情: meta ArticleTitle/PubDate + div#Zoom.TRS_UEDITOR 正文 HTML
特殊: 部分条目为微信外链 mp.weixin.qq.com 跳过; 详情正文 div#trs_editor_view
用法: python3 crawl_jkq_jiujiang_tzgg.py [--pages=N | N]
"""
import re, sys, os, json, html as html_mod, time
from urllib.parse import urljoin
import requests, sqlite3

SITE_NAME = "九江经开区-通知公告"
BASE_URL = "http://jkq.jiujiang.gov.cn"
LIST_URL = "http://jkq.jiujiang.gov.cn/zwzx_303/tzgg/"
LIST_BASE = LIST_URL
DOMAIN = "jkq.jiujiang.gov.cn"
GROUP = "江西"
CUTOFF = "2023-01-01"
DB_PATH = os.environ.get("DB_PATH", "/root/search.db")

HEADERS = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.0.0 Safari/537.36",
    "Referer": LIST_URL,
}

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}"
    return ""

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

def get_page_count(html_text):
    m = re.search(r"createPageHTML\s*\(\s*(\d+)", html_text or "")
    return int(m.group(1)) if m else 1

def extract_list_items(html_text, base_url):
    items = []
    if not html_text:
        return items
    seen = set()
    for m in re.finditer(
        r'<a[^>]*href="([^"]+)"[^>]*title="([^"]*)"[^>]*>(.*?)</a>',
        html_text, re.DOTALL):
        href, title_attr = m.group(1).strip(), m.group(2).strip()
        title = clean_title(title_attr) or clean_title(re.sub(r"<[^>]+>", "", m.group(3)))
        if len(title) < 4:
            continue
        if href in seen:
            continue
        seen.add(href)
        dm = re.search(r"/(\d{6})/t(\d{8})_", href)
        pub_date = ""
        if dm:
            y, mo, d = dm.group(2)[:4], dm.group(2)[4:6], dm.group(2)[6:8]
            pub_date = f"{y}-{mo}-{d}"
        detail_url = urljoin(base_url, href) if not href.startswith("http") else href
        items.append({"title": title, "url": detail_url, "pub_date": pub_date, "href_raw": href})
    return items

def parse_detail(url):
    html_text = fetch(url)
    if not html_text:
        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()))
    pub_date = ""
    m = re.search(r'<meta\s+name="PubDate"\s+content="([^"]*)"', html_text)
    if m:
        pub_date = normalize_date(m.group(1))
    body_html = ""
    # div#Zoom 或 div#trs_editor_view
    m = re.search(r'<div[^>]+id="(?:Zoom|trs_editor_view)"[^>]*>(.*)', html_text, re.DOTALL)
    if m:
        raw = m.group(1)
        cut = re.search(r'</div>\s*<!--|</div>\s*</div>\s*(?:<div[^>]+class="[^"]*(?:footer|share|print)|<ul[^>]+class="[^"]*(?:share|print))', raw)
        if cut:
            body_html = raw[:cut.start() + 6]
        else:
            end = raw.find("</div>")
            body_html = raw[:end + 6] if end != -1 else raw
    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):
            abs_url = href if href.startswith("http") else (BASE_URL + href if href.startswith("/") else urljoin(LIST_BASE, 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 urljoin(LIST_BASE, 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'<div[^>]*class="[^"]*(share|ewm|qrcode|print|bshare)[^"]*"[^>]*>.*?</div>', "", body_html, flags=re.S | re.I)
    body_html = re.sub(r'<p>\s*</p>', "", body_html)
    body_html = re.sub(r'<p[^>]*>', "<p>", body_html)
    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 _store(detail, it):
    row = {
        "site_name": SITE_NAME,
        "source_url": it["url"],
        "page_url": it["url"],
        "title": detail["title"] or it["title"],
        "publish_date": detail["pub_date"] or it["pub_date"],
        "content": detail["content"],
        "summary": (detail["content"] or "")[:500],
        "category": "环境保护",
        "script_name": os.path.basename(__file__),
    }
    conn = sqlite3.connect(DB_PATH, timeout=60)
    conn.execute("PRAGMA busy_timeout=60000")
    c = conn.cursor()
    try:
        c.execute(
            "INSERT OR IGNORE INTO gov_raw (site_name, source_url, page_url, title, publish_date, content, summary, category, script_name) VALUES (?,?,?,?,?,?,?,?,?)",
            (row["site_name"], row["source_url"], row["page_url"], row["title"], row["publish_date"], row["content"], row["summary"], row["category"], row["script_name"]))
        conn.commit()
    except Exception:
        pass
    conn.close()

def crawl(pages=1):
    stored = skipped = 0
    seen_urls = set()
    for page in range(1, pages + 1):
        if page == 1:
            html_text = fetch(LIST_URL)
        else:
            html_text = fetch(f"{LIST_BASE}index_{page}.html")
        if not html_text:
            break
        items = extract_list_items(html_text, LIST_BASE)
        if not items:
            break
        for it in items:
            if it["url"] in seen_urls:
                continue
            seen_urls.add(it["url"])
            # 微信外链跳过
            if "weixin" in it["url"] or "mp.weixin" in it["url"]:
                print(f"  [skip外链] {it['title'][:40]}", flush=True)
                continue
            if not it["pub_date"] or it["pub_date"] < CUTOFF:
                continue
            detail = parse_detail(it["url"])
            if not detail:
                continue
            if not detail.get("content"):
                detail = {"title": it["title"], "publish_date": it["pub_date"], "content": "", "pub_date": it["pub_date"]}
            detail["title"] = detail["title"] or it["title"]
            detail["publish_date"] = detail.get("publish_date") or it["pub_date"]
            _store(detail, it)
            if detail["content"]:
                stored += 1
            else:
                skipped += 1
        print(f"[{SITE_NAME}] P{page}: {len(items)} items", flush=True)
        time.sleep(0.3)
    print(f"[{SITE_NAME}] Result: {stored} stored, {skipped} skipped")

if __name__ == "__main__":
    _MAX_PG = 1
    for a in sys.argv[1:]:
        if a.startswith("--pages="):
            try:
                _MAX_PG = int(a.split("=", 1)[1])
            except ValueError:
                pass
        elif a.isdigit():
            _MAX_PG = int(a)
    crawl(pages=_MAX_PG)
