#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
crawl_huazhou_hpgs.py - 化州市-建设项目环境影响评价信息
http://www.huazhou.gov.cn/zdlyxxgk/hjbh/jsxmhjyxpjxx/
列表: div.list-content > li > a[href=.../content/post_N.html] > div.item-title(标题) + span(日期)
分页: index.html / index_2~12.html (分页器虚报13, P13=404 实际12页, 每页10条)
详情: .../content/post_NNNNNN.html
  → div.article-content > h3(标题) + div.article-subtitle(日期/来源) + div.txt(正文, 含表格)
附件: div.txt 内 a.nfw-cms-attachment (表格单元格内, 绝对URL /attachment/0/x/x/ID.pdf)
广东 post_N 站群模板 (jiangcheng/huizhou 同构)
"""
import sys
import os
import re
import time
import html as html_lib
import urllib.parse
import sqlite3
import json

import requests
from bs4 import BeautifulSoup, Comment

# ---------------- config ----------------
BASE_URL = "http://www.huazhou.gov.cn"
LIST_URL = BASE_URL + "/zdlyxxgk/hjbh/jsxmhjyxpjxx/"
SITE_NAME = "化州市-建设项目环评"
GROUP_NAME = "广东"
SCRIPT_NAME = "crawl_huazhou_hpgs.py"
DB_PATH = os.environ.get("DB_PATH", "/root/search.db")
JSONL_PATH = os.environ.get("JSONL_PATH", "")
ENC = "utf-8"

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

REQUEST_INTERVAL = 1.2
_last_req = 0.0

_MAX_PAGES = 1
for i, a in enumerate(sys.argv):
    if a.startswith("--pages="):
        try:
            _MAX_PAGES = int(a.split("=", 1)[1])
        except ValueError:
            pass
    elif a == "--pages" and i + 1 < len(sys.argv):
        try:
            _MAX_PAGES = int(sys.argv[i + 1])
        except ValueError:
            pass
_PAGES = _MAX_PAGES if _MAX_PAGES >= 1 else 1


def http_get(url, retries=3, timeout=30):
    global _last_req
    dt = time.time() - _last_req
    if dt < REQUEST_INTERVAL:
        time.sleep(REQUEST_INTERVAL - dt)
    _last_req = time.time()
    for i in range(retries):
        try:
            r = requests.get(url, headers=HEADERS, timeout=timeout, verify=False)
            if r.status_code == 200:
                r.encoding = "utf-8"
                return r
        except Exception:
            pass
        time.sleep(2 + i * 2)
    return None


def clean_title(t):
    if not t:
        return ""
    t = html_lib.unescape(t)
    t = t.replace("\u200b", "").replace("\u200c", "").replace("\u200d", "").replace("\ufeff", "")
    t = re.sub(r"\s+", " ", t)
    return t.strip()


def fetch_list(page):
    """抓一页列表, 返回 [(abs_url, title, date)]"""
    if page == 1:
        url = LIST_URL
    else:
        url = LIST_URL + f"index_{page}.html"
    r = http_get(url)
    if r is None:
        return []
    html_text = r.text
    items = []
    for m in re.finditer(r'<a href="(http://www\.huazhou\.gov\.cn/zdlyxxgk/hjbh/jsxmhjyxpjxx/content/post_\d+\.html)"><div class="item-title">([^<]*)</div></a>\s*<span>(\d{4}-\d{2}-\d{2})</span>', html_text):
        abs_url = m.group(1)
        title = clean_title(m.group(2))
        date = m.group(3)
        if title:
            items.append((abs_url, title, date))
    return items


def parse_detail(url):
    """详情页: 返回 (title, pubdate, txt_soup)"""
    r = http_get(url)
    if r is None:
        return None, None, None
    html_text = r.text
    soup = BeautifulSoup(html_text, "html.parser")
    # 标题: div.article-content > h3 优先, fallback meta ArticleTitle
    title = ""
    ac = soup.find("div", class_="article-content")
    if ac:
        h3 = ac.find("h3")
        if h3:
            title = clean_title(h3.get_text())
    if not title:
        tm = re.search(r'<meta name="ArticleTitle" content="([^"]*)"', html_text)
        title = clean_title(tm.group(1)) if tm else ""
    # 日期: meta PubDate 优先, fallback 文本 日期：YYYY-MM-DD
    pubdate = ""
    dm2 = re.search(r'<meta name="PubDate" content="(\d{4}-\d{2}-\d{2})', html_text)
    pubdate = dm2.group(1) if dm2 else ""
    if not pubdate:
        dm = re.search(r"日期[：:]\s*(\d{4}-\d{2}-\d{2})", html_text)
        pubdate = dm.group(1) if dm else ""
    txt = soup.find("div", class_="txt")
    if not txt:
        return title, pubdate, None
    for c in txt.find_all(string=lambda s: isinstance(s, Comment)):
        c.extract()
    return title, pubdate, txt


def html_to_text(txt_soup, abs_url):
    if txt_soup is None:
        return "", False, []
    for tag in txt_soup.find_all(["script", "style", "iframe", "object"]):
        tag.decompose()
    has_table = bool(txt_soup.find("table"))
    attachments = []
    for a in txt_soup.find_all("a", href=True):
        h = a["href"].strip()
        if h.startswith("/") or h.startswith("http"):
            a["href"] = urllib.parse.urljoin(BASE_URL, h)
        if h.lower().endswith((".pdf", ".doc", ".docx", ".xls", ".xlsx", ".zip", ".rar", ".wps", ".7z")) or "upload" in h.lower() or "attach" in h.lower():
            txt = clean_title(a.get_text())
            if txt:
                attachments.append((a["href"], txt))
    for img in txt_soup.find_all("img", src=True):
        s = img["src"].strip()
        if s.startswith("/") or s.startswith("http"):
            img["src"] = urllib.parse.urljoin(BASE_URL, s)
    content = str(txt_soup)
    return content, has_table, attachments


def append_attachments(content, attachments):
    if not attachments:
        return content
    parts = [content] if content.strip() else []
    for abs_url, txt in attachments:
        parts.append(f'<p><a href="{abs_url}" target="_blank">{txt}</a></p>')
    return "\n\n".join(parts)


def load_existing_urls(conn):
    try:
        cur = conn.execute("SELECT page_url FROM gov_raw WHERE site_name=?", (SITE_NAME,))
        return {row[0] for row in cur.fetchall()}
    except Exception:
        return set()


def store_record(conn, url, title, content, date, has_table):
    cur = conn.execute("SELECT id FROM gov_raw WHERE page_url=? AND site_name=?", (url, SITE_NAME))
    if cur.fetchone():
        return False
    try:
        industry = "other"
        try:
            from crawler_lib import classify_industry
            industry = classify_industry(title)
        except Exception:
            pass
        cur = conn.execute(
            "INSERT OR IGNORE INTO gov_raw "
            "(page_url, source_url, title, content, publish_date, site_name, group_name, script_name, has_table, industry) "
            "VALUES (?,?,?,?,?,?,?,?,?,?)",
            (url, url, title, content, date, SITE_NAME, GROUP_NAME, SCRIPT_NAME, has_table, industry),
        )
        if cur.rowcount > 0:
            summary = re.sub(r"<[^>]+>", "", content)
            summary = html_lib.unescape(summary)
            summary = re.sub(r"\s+", " ", summary).strip()[:200]
            conn.execute(
                "INSERT OR IGNORE INTO gov_search (rowid, title, site_name, summary) VALUES (?,?,?,?)",
                (cur.lastrowid, title, SITE_NAME, summary),
            )
            return True
        return False
    except sqlite3.OperationalError as e:
        if "locked" in str(e):
            time.sleep(3)
            return store_record(conn, url, title, content, date, has_table)
        raise


def main():
    conn = None
    if not JSONL_PATH:
        conn = sqlite3.connect(DB_PATH, timeout=60)
        conn.execute("PRAGMA busy_timeout=60000")
        conn.execute("PRAGMA journal_mode=WAL")
        existing = load_existing_urls(conn)
        print(f"已入库 {len(existing)} 条, 用于列表级预查重", flush=True)

    new_count = 0
    skip_count = 0
    jsonl_rows = []

    for page in range(1, _PAGES + 1):
        items = fetch_list(page)
        print(f"[list] page={page} items={len(items)}", flush=True)
        if not items:
            print("Empty page, stop pagination", flush=True)
            break
        for abs_url, title, date in items:
            if not JSONL_PATH and abs_url in existing:
                skip_count += 1
                continue
            dtitle, ddate, txt = parse_detail(abs_url)
            if txt is None:
                print(f"  skip empty: {title[:30]} | {abs_url}", flush=True)
                skip_count += 1
                continue
            if not dtitle:
                dtitle = title
            if not ddate:
                ddate = date
            content, has_table, atts = html_to_text(txt, abs_url)
            content = append_attachments(content, atts)
            plain_len = len(re.sub(r"<[^>]+>", "", content).strip())
            if plain_len < 10 and "<img" not in content and not atts:
                print(f"  skip empty: {dtitle[:30]} | {abs_url}", flush=True)
                skip_count += 1
                continue
            if JSONL_PATH:
                jsonl_rows.append({
                    "page_url": abs_url, "title": dtitle, "content": content,
                    "publish_date": ddate, "has_table": has_table,
                    "site_name": SITE_NAME, "group_name": GROUP_NAME,
                    "script_name": SCRIPT_NAME,
                })
                print(f"  JSONL + {dtitle[:40]} ({ddate})", flush=True)
                new_count += 1
                continue
            ok = store_record(conn, abs_url, dtitle, content, ddate, has_table)
            if ok:
                new_count += 1
                existing.add(abs_url)
                print(f"  + {dtitle[:40]} ({ddate})", flush=True)
            else:
                skip_count += 1

    if JSONL_PATH:
        with open(JSONL_PATH, "w", encoding="utf-8") as f:
            for row in jsonl_rows:
                f.write(json.dumps(row, ensure_ascii=False) + "\n")
        print(f"JSONL written: {JSONL_PATH} ({len(jsonl_rows)} rows)", flush=True)

    if conn is not None:
        conn.commit()
        conn.close()
    print(f"[done] new={new_count} skip={skip_count}", flush=True)


if __name__ == "__main__":
    main()
