#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
crawl_huaqing_hpgs.py - 黄冈市华清生态环境咨询有限公司-环保公示
http://www.huaqingeec.com/index.php?c=content&a=list&catid=46 (环境影响评价公示)
                             catid=47 (竣工环保验收公示)
列表: div.new1 > ul > li > a[href='/index.php?c=content&a=show&id=N'](单引号) > 标题 + font 日期
分页: ?c=content&a=list&catid=N&page=M (catid46: 47条5页 / catid47: 93条10页)
详情: ?c=content&a=show&id=N
  → div.product_title(标题) + div.product_related(修改时间) + 无名div正文(<p><span>段落, 含百度网盘链接)
附件: 无 (纯文本公示, 网盘链接在正文内)
一脚本多栏目: --col=46|47 两条独立配置 (site_name 区分)
"""
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.huaqingeec.com"
COLUMNS = {
    "46": {"catid": "46", "site_name": "黄冈华清-环境影响评价公示"},
    "47": {"catid": "47", "site_name": "黄冈华清-竣工环保验收公示"},
}
DEFAULT_COL = "46"
GROUP_NAME = "湖北"
SCRIPT_NAME = "crawl_huaqing_hpgs.py"
DB_PATH = os.environ.get("DB_PATH", "/root/search.db")
JSONL_PATH = os.environ.get("JSONL_PATH", "")
ENC = "utf-8"

# 解析 --col
_COL = DEFAULT_COL
for i, a in enumerate(sys.argv):
    if a.startswith("--col="):
        _COL = a.split("=", 1)[1]
    elif a == "--col" and i + 1 < len(sys.argv):
        _COL = sys.argv[i + 1]
if _COL not in COLUMNS:
    print(f"未知 --col={_COL}, 可用: {list(COLUMNS.keys())}")
    sys.exit(1)
SITE_NAME = COLUMNS[_COL]["site_name"]
CATID = COLUMNS[_COL]["catid"]
LIST_URL = f"{BASE_URL}/index.php?c=content&a=list&catid={CATID}"

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",
    "Referer": LIST_URL,
}

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"&page={page}"
    r = http_get(url)
    if r is None:
        return []
    html_text = r.text
    items = []
    for m in re.finditer(r"<li><a href='([^']+)'[^>]*>([^<]+)</a><font[^>]*>([^<]*)</font></li>", html_text):
        href = m.group(1)
        title = clean_title(m.group(2))
        date = m.group(3).strip()
        abs_url = urllib.parse.urljoin(BASE_URL, href) if href.startswith("/") else href
        if title:
            items.append((abs_url, title, date))
    return items


def parse_detail(url):
    """详情页: 返回 (title, pubdate, body_soup)"""
    r = http_get(url)
    if r is None:
        return None, None, None
    html_text = r.text
    soup = BeautifulSoup(html_text, "html.parser")
    # 标题: div.product_title
    title = ""
    pt = soup.find("div", class_="product_title")
    if pt:
        title = clean_title(pt.get_text())
    # 日期: product_related 内 修改时间：YYYY-MM-DD
    pubdate = ""
    pr = soup.find("div", class_="product_related")
    if pr:
        dm = re.search(r"(\d{4}-\d{2}-\d{2})", pr.get_text())
        pubdate = dm.group(1) if dm else ""
    # 正文: div.content 内含 <p> 段落最多的 div (排除 上一个/下一篇/print 页脚)
    body = None
    content_div = soup.find("div", class_="content")
    if content_div:
        divs = content_div.find_all("div", recursive=False)
        best = None
        best_ps = -1
        for d in divs:
            ps = len(d.find_all("p"))
            txt = d.get_text().strip()
            if ps > best_ps and len(txt) > 20:
                best = d
                best_ps = ps
        body = best if best is not None else content_div
    return title, pubdate, body


def html_to_text(body, abs_url):
    if body is None:
        return "", False, []
    for tag in body.find_all(["script", "style", "iframe", "object"]):
        tag.decompose()
    has_table = bool(body.find("table"))
    attachments = []
    for a in body.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 body.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(body)
    # 规范化 <p style=...> → <p> (search_app 检测闭合 <p> 走 HTML 渲染, meeb/濂溪教训)
    content = re.sub(r"<p[^>]*>", "<p>", content)
    # 剥外层 <div> 包装 (只留段落/表格)
    content = re.sub(r"^<div[^>]*>", "", content)
    content = re.sub(r"</div>\s*$", "", content)
    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] col={CATID} 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, body = parse_detail(abs_url)
            if body 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(body, 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] col={CATID} new={new_count} skip={skip_count}", flush=True)


if __name__ == "__main__":
    main()
