#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
抚州市生态环境局 - 双公示/拟批准公示 爬虫
列表: http://hbj.jxfz.gov.cn/col/col8955/index.html (双公示 45条静态)
      http://hbj.jxfz.gov.cn/col/col4375/index.html (拟批准公示 5条静态)
  注意: 域名是 hbj.jxfz.gov.cn (非 sthj.jxfz.gov.cn)
  列表: 静态 HTML dataStore (script type=text/xml) 含记录, jpage API dataproxy 已失效
详情: /art/YYYY/M/D/art_XXXX_YYYY.html
  标题: <meta name="ArticleTitle"> (完整)
  正文: <div class="bfr_article_content">
用法: python3 crawl_fz_hbj_tzgg.py [--limit=N]
"""
import os, sys, re, time, json, html as html_mod
import requests
from urllib.parse import urljoin

sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from crawler_lib import push_to_searchdb

BASE_URL = "http://hbj.jxfz.gov.cn"
SITE_NAME = "抚州市生态环境局-双公示"
CATEGORY = "公示公告"
LIST_URLS = [
    ("双公示专栏", "http://hbj.jxfz.gov.cn/col/col8955/index.html"),
    ("拟批准公示", "http://hbj.jxfz.gov.cn/col/col4375/index.html"),
]

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


def parse_args():
    limit = 0
    for a in sys.argv[1:]:
        if a.startswith("--limit="):
            limit = int(a.split("=")[1])
    return limit


def clean_title(t):
    t = html_mod.unescape(t or "")
    t = re.sub(r"[\u200b\u200e\u200f\ufeff\xa0]", "", t)
    t = re.sub(r"\s+", " ", t)
    t = re.sub(r"^[•·\-—]\s*", "", t)
    return t.strip()


def parse_datastore(html):
    """从静态页 dataStore 解析记录列表"""
    items = []
    seen = set()
    for rec in re.findall(r"<record><!\[CDATA\[(.*?)\]\]></record>", html, re.S):
        am = re.search(r"""href=['"]([^'"]*art_\d+_\d+\.html[^'"]*)['"]""", rec)
        if not am:
            am = re.search(r"(art_\d+_\d+\.html)", rec)
        if not am:
            continue
        href = am.group(1)
        if href in seen:
            continue
        seen.add(href)
        href = urljoin(BASE_URL, href) if not href.startswith("http") else href
        # 标题: title= 属性 (单双引号均可)
        tm = re.search(r"""title=['"]([^'"]*)['"]""", rec)
        if not tm:
            tm = re.search(r">([^<]{6,})</a>", rec)
        title = clean_title(tm.group(1)) if tm else ""
        if len(title) < 4:
            continue
        date = ""
        dm = re.search(r"(\d{4})-(\d{2})-(\d{2})", rec)
        if dm:
            date = "%s-%s-%s" % dm.groups()
        items.append({"title": title, "href": href, "date": date})
    return items


def fetch_list(session, url):
    try:
        r = session.get(url, timeout=30)
        r.encoding = "utf-8"
        return parse_datastore(r.text)
    except Exception as e:
        print(f"    [ERR] list {url}: {e}", flush=True)
        return []


def fetch_detail(session, url):
    """详情: meta ArticleTitle + div.bfr_article_content"""
    try:
        r = session.get(url, headers={"User-Agent": UA, "Referer": BASE_URL + "/"}, timeout=30)
        r.encoding = "utf-8"
        html = r.text
        title = ""
        m = re.search(r'<meta name="ArticleTitle" content="([^"]*)"', html)
        if m:
            title = clean_title(m.group(1))
        if not title:
            m = re.search(r"<h1[^>]*>([^<]+)</h1>", html)
            if m:
                title = clean_title(m.group(1))
        pub_date = ""
        m = re.search(r'<meta name="PubDate" content="([^"]*)"', html)
        if m:
            pub_date = m.group(1).strip()[:10]
        if not pub_date:
            m = re.search(r"(\d{4})-(\d{1,2})-(\d{1,2})", html)
            if m:
                pub_date = "%s-%02d-%02d" % (m.group(1), int(m.group(2)), int(m.group(3)))
        # 正文: div.bfr_article_content (或 div#zoom / div.TRS_UEDITOR)
        body = ""
        for cid in ['class="bfr_article_content"', 'id="zoom"', 'class="TRS_UEDITOR"', 'class="content"']:
            i = html.find(cid)
            if i >= 0:
                start = html.find(">", i) + 1
                depth = 0
                j = start
                while j < len(html):
                    if html[j:j+4] == "<div":
                        depth += 1
                        j += 4
                    elif html[j:j+6] == "</div>":
                        depth -= 1
                        j += 6
                        if depth == 0:
                            break
                    else:
                        j += 1
                raw = html[start:j-6]
                raw = re.sub(r"<script[\s\S]*?</script>", "", raw)
                raw = re.sub(r"<style[\s\S]*?</style>", "", raw)
                raw = re.sub(r'href="([^"]*)"', lambda m: 'href="%s"' % (urljoin(url, m.group(1)) if not m.group(1).startswith(("http", "#", "javascript")) else m.group(1)), raw)
                raw = re.sub(r'src="([^"]*)"', lambda m: 'src="%s"' % (urljoin(url, m.group(1)) if not m.group(1).startswith(("http", "data:", "javascript")) else m.group(1)), raw)
                raw = re.sub(r'\sstyle="[^"]*"', "", raw)
                raw = re.sub(r"<span[^>]*>|</span>|<strong[^>]*>|</strong>|<b[^>]*>|</b>|<font[^>]*>|</font>", "", raw)
                body = raw.strip()
                if len(body) >= 20:
                    break
        if not body or len(body) < 20:
            body = ""
        return title, pub_date, body
    except Exception as e:
        print(f"    [ERR] detail {url}: {e}", flush=True)
        return "", "", ""


def main():
    limit = parse_args()
    print(f"[FZ-HBJ] SITE={SITE_NAME}", flush=True)

    session = requests.Session()
    session.headers.update({"User-Agent": UA})
    try:
        session.get(BASE_URL + "/", timeout=20)
    except Exception:
        pass

    all_items = []
    seen = set()
    for col_name, url in LIST_URLS:
        items = fetch_list(session, url)
        new_count = 0
        for it in items:
            if it["href"] in seen:
                continue
            seen.add(it["href"])
            all_items.append(it)
            new_count += 1
        print(f"  [{col_name}] {len(items)}条(新{new_count})", flush=True)
        time.sleep(0.4)

    print(f"列表完成: {len(all_items)} 条, 抓详情...", flush=True)
    if limit and len(all_items) > limit:
        all_items = all_items[:limit]

    results = []
    for i, it in enumerate(all_items):
        d_title, d_date, body = fetch_detail(session, it["href"])
        title = d_title or it["title"]
        pub_date = d_date or it.get("date", "")
        summary = re.sub(r"<[^>]+>", " ", body) if body else title
        summary = re.sub(r"\s+", " ", summary).strip()[:300]
        atts = []
        if body:
            for m in re.finditer(r'<a[^>]*href="([^"]*\.(?:pdf|doc|docx|xls|xlsx|zip|rar|ofd|wps))"[^>]*>([^<]*)</a>', body, re.I):
                atts.append({"name": m.group(2).strip(), "url": m.group(1)})
        results.append({
            "site_name": SITE_NAME, "source_url": it["href"], "url": it["href"],
            "title": title, "pub_date": pub_date, "content": body,
            "summary": summary, "category": CATEGORY,
            "attachments": json.dumps(atts, ensure_ascii=False) if atts else "",
        })
        if (i + 1) % 10 == 0:
            print(f"  detail {i+1}/{len(all_items)}", flush=True)
        time.sleep(0.3)

    print(f"  pushing {len(results)} items to searchdb...", flush=True)
    push_to_searchdb(results, batch_label=SITE_NAME)
    empty = sum(1 for r in results if not (r.get("content") or "").strip())
    print(f"  DONE. pushed={len(results)} 空正文={empty}", flush=True)


if __name__ == "__main__":
    main()
