#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
南平市生态环境局 - 公示公告 (gsgg) 爬虫
列表: https://hbj.np.gov.cn/cms/html/npshjbhj/gsgg/index.html
  YLCMS 架构, 静态分页 ?page=N (共50页)
详情: /cms/html/npshjbhj/YYYY-MM-DD/NUMBER.html
  正文: <DIV class="content" id="Content">
用法: python3 crawl_np_hbj_gsgg.py [--pages=N] [--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 = "https://hbj.np.gov.cn"
LIST_URL = BASE_URL + "/cms/html/npshjbhj/gsgg/index.html"
# 分页走 sitemanage (gsgg/index.html?page=N 无效)
LIST_PAGE_URL = BASE_URL + "/cms/sitemanage/index.shtml?siteId=100433125043450000&page={}"
SITE_NAME = "南平市生态环境局-公示公告"
CATEGORY = "公示公告"
MAX_PAGES = 50

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, "Referer": BASE_URL + "/cms/html/npshjbhj/gsgg/index.html"}


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


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


def fetch_list(session, page):
    if page == 1:
        url = LIST_URL
    else:
        url = LIST_PAGE_URL.format(page)
    try:
        r = session.get(url, timeout=30)
        r.encoding = "utf-8"
        html = r.text
        items = []
        seen = set()
        for m in re.finditer(r"""<A\s+href="([^"]*cms/html/npshjbhj/\d{4}-\d{2}-\d{2}/\d+\.html)"[^>]*>([^<]*)</A>""", html, re.I):
            href, title = m.group(1), m.group(2).strip()
            if href in seen:
                continue
            seen.add(href)
            href = urljoin(BASE_URL, href) if not href.startswith("http") else href
            t = clean_title(title)
            if len(t) < 4 or "联系我们" in t or "访问统计" in t:
                continue
            date = ""
            dm = re.search(r"(\d{4})-(\d{2})-(\d{2})", href)
            if dm:
                date = "%s-%s-%s" % dm.groups()
            items.append({"title": t, "href": href, "date": date})
        return items
    except Exception as e:
        print(f"    [ERR] list page {page}: {e}", flush=True)
        return []


def fetch_detail(session, url):
    """详情: <DIV class="content" id="Content">  (用 BeautifulSoup 提取, 避免深度匹配吃进页脚)"""
    try:
        r = session.get(url, headers=HEADERS, timeout=30)
        r.encoding = "utf-8"
        html = r.text
        title = ""
        m = re.search(r"<title>([^<]+)</title>", html)
        if m:
            title = clean_title(m.group(1).split("_")[0].split("-")[0])
        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)))
        body = ""
        from bs4 import BeautifulSoup
        soup = BeautifulSoup(html, "html.parser")
        for sel in ['#Content', 'div.content', '.TRS_Editor', '.view']:
            el = soup.select_one(sel)
            # 有图无文(扫描件公示)也算有效正文
            if not el or (len(el.get_text(" ", strip=True)) < 20 and not el.find("img")):
                continue
            for bad in el.select("script, style"):
                bad.decompose()
            # 清理尾部噪音: 二维码容器 + 扫一扫/分享/打印 按钮
            for bad_sel in ['.ewm', '.ewm-1', '.ewm-2', '.ewm_box', '.qrcode']:
                for b in el.select(bad_sel):
                    b.decompose()
            for node in el.find_all(string=re.compile(r"扫一扫|分享到|打印本页|关闭窗口|手机打开")):
                p = node.find_parent("p") or node.find_parent("div")
                if p:
                    p.decompose()
            raw = str(el)
            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)
            raw = re.sub(r"<p[^>]*>\s*(?:扫一扫|分享到|打印本页)[^<]*</p>", "", 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():
    max_pages, limit = parse_args()
    if not max_pages:
        max_pages = MAX_PAGES
    print(f"[NP-HBJ] SITE={SITE_NAME} max_pages={max_pages}", flush=True)

    session = requests.Session()
    session.headers.update({"User-Agent": UA})

    all_items = []
    seen = set()
    for pg in range(1, max_pages + 1):
        items = fetch_list(session, pg)
        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"  Page {pg}: {len(items)}条(新{new_count}) 累计{len(all_items)}", flush=True)
        if not items:
            print(f"  [END] page {pg} empty", flush=True)
            break
        time.sleep(0.3)

    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"]
        # 优先用列表日期 (URL 内 YYYY-MM-DD), 详情页日期可能匹配到页面其他位置
        pub_date = it.get("date", "") or d_date or ""
        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.2)

    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()
