#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
兖矿鲁南化工 - 公告公示
站点: lnhg.shandong-energy.com/90745/90751/
CMS: litenews JSONP API (山东能源集团站群)
列表: GET https://app.litenews.cn/v1/app/article/common/json?page=N&cateid=90751&_orgid_=393&cqcallback=cb
      JSONP data.infos[]: title/url/publish_at/desc(copyfrom)
详情: https://lnhg.shandong-energy.com/90745/90751/2026/05/43712035.html (div#inner_content 正文 + 附件)
用法: python3 crawl_lnhg_gsgg.py [--pages=N | N]
"""
import re, sys, os, json, html as html_mod
from urllib.parse import urljoin
import requests, sqlite3

SITE_NAME = "兖矿鲁南化工-公告公示"
BASE_URL = "https://lnhg.shandong-energy.com"
API_URL = "https://app.litenews.cn/v1/app/article/common/json"
CATEID = "90751"
ORGID = "393"
DOMAIN = "lnhg.shandong-energy.com"
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": f"{BASE_URL}/90745/90751/",
}

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(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:
                import time; time.sleep(2)
    return None

def fetch_list_page(page):
    url = f"{API_URL}?page={page}&cateid={CATEID}&_orgid_={ORGID}&cqcallback=cb"
    text = fetch(url)
    if not text:
        return []
    m = re.match(r'cb\((.*)\)\s*;?\s*$', text, re.S)
    if not m:
        return []
    try:
        j = json.loads(m.group(1))
    except Exception:
        return []
    items = []
    for d in j.get("data", {}).get("infos", []):
        title = clean_title(d.get("title", ""))
        u = d.get("url", "")
        date = (d.get("publish_at") or "")[:10]
        desc = d.get("desc", "") or ""
        if not title or not u:
            continue
        items.append({"title": title, "url": u, "pub_date": date, "desc": desc})
    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'<div[^>]+class="[^"]*news_title[^"]*"[^>]*>(.*?)</div>', 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*.*$", "", m.group(1).strip()))
    pub_date = ""
    m = re.search(r'<meta\s+name="PubDate"\s+content="([^"]*)"', html_text)
    if m:
        pub_date = m.group(1)[:10]
    if not pub_date:
        m = re.search(r'20\d{2}[-/年]\d{1,2}[-/月]\d{1,2}', html_text[:3000])
        if m:
            pub_date = re.sub(r'[年月/]', '-', m.group(0))[:10]
    # 正文 div.inner_content (class 或 id)
    body_html = ""
    i = html_text.find('class="inner_content')
    if i < 0:
        i = html_text.find('id="inner_content"')
    if i >= 0:
        ds = html_text.rfind('<div', 0, i)
        if ds >= 0:
            s = html_text[ds:]
            d = 0
            for j in range(len(s)):
                if s[j:j+4] == "<div" and (j+4 >= len(s) or s[j+4] in " >\n\r\t"):
                    d += 1
                elif s[j:j+6] == "</div>":
                    d -= 1
                    if d == 0:
                        gt = s.find(">", 0, j)
                        body_html = s[gt+1:j] if gt > 0 else ""
                        break
    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)
    # 附件 (img11.litenews.cn 等)
    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(url, 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(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>\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):
        items = fetch_list_page(page)
        if not items:
            break
        for it in items:
            if it["url"] in seen_urls:
                continue
            seen_urls.add(it["url"])
            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__":
    import time
    _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)
