#!/usr/bin/env python3
"""
广东华博士环保科技有限公司 - 环评公示
http://www.zhhbs.com/list/181.html
自定义 PHP CMS (enetcms)
"""
import json, re, sys, time, requests
from bs4 import BeautifulSoup
from urllib.parse import urljoin

DB_PATH = "/root/search.db"
SITE_NAME = "华博士环保-环评公示"
CATEGORY = "广东"
BASE_URL = "http://www.zhhbs.com/list/181.html"
MAX_PAGES = 5

HEADERS = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.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,en;q=0.8",
    "Referer": "http://www.zhhbs.com/",
}
INSERT_SQL = """INSERT OR IGNORE INTO gov_raw 
    (site_name, page_url, title, publish_date, summary, content, category, attachments)
    VALUES (?, ?, ?, ?, '', ?, ?, ?)"""


def init_db():
    import sqlite3
    conn = sqlite3.connect(DB_PATH, timeout=60)
    conn.execute("PRAGMA journal_mode=WAL")
    conn.execute("PRAGMA busy_timeout=5000")
    return conn


def fetch(url, timeout=30):
    r = requests.get(url, headers=HEADERS, timeout=timeout)
    r.encoding = "utf-8"
    return r


def table_to_markdown(table, *args, **kwargs):
    """保留 HTML 表格结构（不转 md）"""
    return str(table)

def extract_list_page(page_num):
    if page_num == 1:
        url = BASE_URL
    else:
        url = f"http://www.zhhbs.com/content/index/menuId/181/p/{page_num}.html"
    
    try:
        r = fetch(url)
    except Exception as e:
        print(f"  [ERROR] Page {page_num}: {e}", flush=True)
        return []
    if r.status_code != 200:
        print(f"  [ERROR] HTTP {r.status_code} page {page_num}", flush=True)
        return []

    soup = BeautifulSoup(r.text, "html.parser")
    items = []
    
    for a in soup.find_all("a", href=True):
        href = a["href"]
        if "/list/info/" not in href:
            continue
        title = a.get("title", "").strip()
        if not title:
            title = a.get_text(strip=True)
        if not title:
            continue
        full_url = urljoin("http://www.zhhbs.com/", href)
        items.append({"title": title, "url": full_url})
    
    print(f"  Page {page_num}: {len(items)} items", flush=True)
    return items


def extract_detail(url):
    try:
        r = fetch(url)
    except Exception as e:
        print(f"  [ERROR] {url}: {e}", flush=True)
        return None
    if r.status_code != 200:
        return None

    soup = BeautifulSoup(r.text, "html.parser")
    
    # Content div
    content_div = soup.select_one("div.content.content-txt.content-bg")
    if not content_div:
        content_div = soup.select_one("div.content")
    if not content_div:
        return None

    # Title from .content-tit
    title = ""
    title_el = content_div.select_one(".content-tit")
    if title_el:
        title = title_el.get_text(strip=True)

    # Date from .time
    pub_date = ""
    date_el = content_div.select_one(".time")
    if date_el:
        dt = date_el.get_text(strip=True)
        dt = dt.replace("发布日期：", "").replace("发布时间：", "").strip()
        pub_date = dt

    # Extract content from .content-mess
    content_text = ""
    content_mess = content_div.select_one(".content-mess")
    if not content_mess:
        content_mess = content_div

    parts = []
    for child in content_mess.children:
        if child.name is None:
            continue
        tn = child.name.lower()
        if tn == "p":
            txt = child.get_text(" ", strip=True)
            if txt:
                parts.append(txt)
        elif tn == "table":
            md = table_to_markdown(child)
            if md:
                parts.append(md)
        elif tn in ("div", "center", "section"):
            for p in child.find_all("p", recursive=False):
                txt = p.get_text(" ", strip=True)
                if txt:
                    parts.append(txt)
            for t in child.find_all("table", recursive=False):
                md = table_to_markdown(t)
                if md:
                    parts.append(md)
            remaining = child.get_text(" ", strip=True).strip()
            # Skip if it duplicates extracted text
        elif tn in ("script", "style", "br"):
            continue
        else:
            txt = child.get_text(" ", strip=True)
            if txt:
                parts.append(txt)

    content_text = "\n\n".join(parts)

    # Attachments - look for file download links
    attachments_list = []
    for a_tag in content_div.find_all("a", href=True):
        h = a_tag["href"]
        if re.search(r'\.(pdf|doc|docx|xls|xlsx|rar|zip)$', h, re.IGNORECASE) and "javascript" not in h:
            at = a_tag.get_text(strip=True) or h.split("/")[-1]
            fu = urljoin(url, h)
            attachments_list.append({"name": at, "url": fu})

    if len(content_text.strip()) < 20:
        content_text = f'<p><a href="{url}">{title}</a></p>\n（本文为PDF附件）'

    return {
        "title": title,
        "content": content_text,
        "pub_date": pub_date,
        "attachments": json.dumps(attachments_list, ensure_ascii=False) if attachments_list else "",
    }


def crawl(test_mode=False, max_pages=MAX_PAGES):
    print(f"[{SITE_NAME}] Starting, max_pages={max_pages}", flush=True)
    conn = init_db()
    cur = conn.cursor()
    total_inserted = total_skipped = pages_crawled = 0

    for pn in range(1, max_pages + 1):
        items = extract_list_page(pn)
        if not items:
            print(f"  Page {pn} empty, stop", flush=True)
            break
        pages_crawled += 1
        for item in items:
            title, url = item["title"], item["url"]
            cur.execute("SELECT id FROM gov_raw WHERE page_url = ?", (url,))
            if cur.fetchone():
                total_skipped += 1
                continue
            detail = extract_detail(url)
            if detail is None:
                total_skipped += 1
                continue
            # Use detail title (cleaner, without date prefix from list)
            if detail["title"]:
                title = detail["title"]
            content = detail["content"]
            pub_date = detail["pub_date"]
            attachments = detail["attachments"]
            cur.execute(INSERT_SQL, (
                SITE_NAME, url, title, pub_date,
                content, CATEGORY, attachments,
            ))
            total_inserted += 1
            if test_mode and total_inserted >= 10:
                break
        conn.commit()
        if test_mode and total_inserted >= 10:
            print(f"  Test: stop after {total_inserted}", flush=True)
            break
        time.sleep(1)
    conn.close()
    print(f"[{SITE_NAME}] Done. Inserted={total_inserted}, Skipped={total_skipped}, Pages={pages_crawled}", flush=True)
    return total_inserted


if __name__ == "__main__":
    test_mode = "--test" in sys.argv
    mp = 3 if test_mode else MAX_PAGES
    if "--max-pages" in sys.argv:
        idx = sys.argv.index("--max-pages")
        if idx + 1 < len(sys.argv):
            mp = int(sys.argv[idx + 1])
    crawl(test_mode=test_mode, max_pages=mp)
