#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
宜城市生态环境局 - 其他主动公开内容 爬虫
CMS: TRS (TRS_UEDITOR)
List: /xxgk/bmptlj/bm/sthjj/fdzdgknr/qtzdgknr_18348/ 
Pagination: index.shtml (P1), index_{N-1}.shtml (PN, N>=2)
Detail: /2026MM/tYYYYMMDD_XXXXXXX.shtml
每页20条
"""

import requests, re, json, sqlite3, time, sys
from bs4 import BeautifulSoup
from urllib.parse import urljoin

DB_PATH = "/root/search.db"
SITE_NAME = "宜城市生态环境局-其他主动公开内容"
CATEGORY = "其他主动公开内容"
GROUP = "湖北"
BASE_URL = "http://www.ych.gov.cn"
LIST_PATH = "/xxgk/bmptlj/bm/sthjj/fdzdgknr/qtzdgknr_18348"
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-Language": "zh-CN,zh;q=0.9",
}

SKIP_TEXTS = [
    "【打印本页】", "【关闭窗口】", "打印本页", "关闭窗口",
    "转载分享：", "浏览量：", "相关附件：", "相关稿件：",
    "扫一扫在手机打开", "附件：",
]


# ---------- Table to Markdown ----------

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

def render_paragraph(p_tag, detail_url):
    """Render a <p> preserving <a> and <img>."""
    parts = []
    for elem in p_tag.contents:
        if isinstance(elem, str):
            t = elem.strip()
            if t:
                parts.append(t)
        elif elem.name == "a":
            href = elem.get("href", "").strip()
            text = elem.get_text(strip=True)
            if href and text:
                full = urljoin(detail_url, href) if not href.startswith("http") else href
                parts.append(f"[{text}]({full})")
            elif text:
                parts.append(text)
        elif elem.name == "img":
            src = elem.get("src", "")
            if src:
                alt = elem.get("alt", "")
                full_src = urljoin(detail_url, src) if not src.startswith("http") else src
                parts.append(f"![{alt}]({full_src})" if alt else f"![]({full_src})")
        elif elem.name in ("b", "strong", "span", "font", "em"):
            t = elem.get_text(" ", strip=True)
            if t:
                parts.append(t)
        elif elem.name == "br":
            parts.append("\n")
        elif hasattr(elem, "get_text"):
            t = elem.get_text(" ", strip=True)
            if t:
                parts.append(t)
    return " ".join(parts)


def extract_content(content_div, detail_url):
    """Extract content: paragraphs + tables + images via recursive find_all."""
    parts = []
    processed = set()

    for child in content_div.children:
        if child.name is None:
            continue
        tn = child.name.lower()

        if tn == "p":
            txt = render_paragraph(child, detail_url)
            if txt:
                parts.append(txt)

        elif tn == "table":
            all_text = child.get_text(strip=True)
            if len(all_text) < 15:
                continue
            md = table_to_md(child)
            if md:
                parts.append(md)

        elif tn == "img":
            src = child.get("src", "")
            if src and id(child) not in processed:
                processed.add(id(child))
                alt = child.get("alt", "")
                full_src = urljoin(detail_url, src) if not src.startswith("http") else src
                parts.append(f"![{alt}]({full_src})" if alt else f"![]({full_src})")

        elif tn in ("div", "section", "article"):
            # Recursively handle sub-elements
            for sub in child.find_all(["p", "table", "img"], recursive=True):
                if id(sub) in processed:
                    continue
                processed.add(id(sub))
                if sub.name == "p":
                    # Skip empty <p><br/></p>
                    txt = sub.get_text(" ", strip=True)
                    if not txt:
                        continue
                    rendered = render_paragraph(sub, detail_url)
                    if rendered:
                        parts.append(rendered)
                elif sub.name == "table":
                    all_text = sub.get_text(strip=True)
                    if len(all_text) < 15:
                        continue
                    md = table_to_md(sub)
                    if md:
                        parts.append(md)
                elif sub.name == "img":
                    src = sub.get("src", "")
                    if src:
                        alt = sub.get("alt", "")
                        full_src = urljoin(detail_url, src) if not src.startswith("http") else src
                        parts.append(f"![{alt}]({full_src})" if alt else f"![]({full_src})")

        elif tn in ("ul", "ol"):
            for li in child.find_all("li", recursive=False):
                txt = li.get_text(" ", strip=True)
                if txt:
                    parts.append("- " + txt)

    # Filter noise
    filtered = []
    for p in parts:
        if any(sk in p for sk in SKIP_TEXTS):
            continue
        if re.match(r'^(来源|发布日期)[：:]\s*', p):
            continue
        filtered.append(p)

    return "\n\n".join(filtered)


# ---------- Attachments ----------

def extract_attachments(soup):
    atts = []
    seen = set()
    for a in soup.find_all("a", href=True):
        href = a["href"]
        if re.search(r"\.(pdf|doc|docx|xls|xlsx|rar|zip|txt)$", href, re.I):
            if href.startswith("/"):
                href = BASE_URL + href
            elif not href.startswith("http"):
                href = BASE_URL + "/" + href.lstrip("/")
            name = a.get_text(strip=True) or href.split("/")[-1].split("?")[0]
            if href not in seen:
                seen.add(href)
                atts.append({"name": name, "url": href})
    return atts


# ---------- Detail ----------

def fetch_detail(url, list_title=""):
    try:
        r = requests.get(url, headers=HEADERS, timeout=20)
        r.encoding = "utf-8"
        html = r.text
    except Exception as e:
        return None, None, None, []

    soup = BeautifulSoup(html, "html.parser")

    # Title
    title = ""
    mt = soup.find("meta", attrs={"name": "ArticleTitle"})
    if mt and mt.get("content"):
        title = mt["content"].strip()
    if not title:
        ttag = soup.find("title")
        if ttag:
            title = ttag.get_text(strip=True)
            title = re.sub(r"\s*-\s*宜城市人民政府门户网站\s*$", "", title).strip()
    if not title:
        title = list_title

    # Date
    date_str = ""
    md = soup.find("meta", attrs={"name": "PubDate"})
    if md and md.get("content"):
        date_str = md["content"].strip()[:10]

    # Content: TRS_UEDITOR
    content_div = soup.find("div", class_="TRS_UEDITOR")
    if not content_div:
        content_div = soup.find("div", class_="view")
    # The TRS_UEDITOR div may be wrapped in a <p> tag
    if not content_div:
        for p in soup.find_all("p"):
            inner = p.find("div", class_="view")
            if inner:
                content_div = inner
                break

    attachments = extract_attachments(soup)

    if content_div:
        content = extract_content(content_div, url)
    else:
        content = ""

    # Fallback for empty content
    if len(content.strip()) < 20:
        content = f"[{title}]({url})"
        if attachments:
            for a in attachments:
                content += f"\n\n附件：[{a['name']}]({a['url']})"

    return title, date_str, content, attachments


# ---------- List ----------

def extract_list_page(page_num):
    """Extract articles from page N (1-indexed)."""
    if page_num == 1:
        url = f"{BASE_URL}{LIST_PATH}/"
    else:
        # index_{N-1}.shtml
        url = f"{BASE_URL}{LIST_PATH}/index_{page_num - 1}.shtml"

    try:
        r = requests.get(url, headers=HEADERS, timeout=20)
        r.encoding = "utf-8"
    except Exception as e:
        print(f"  Page {page_num} error: {e}")
        return []

    soup = BeautifulSoup(r.text, "html.parser")

    articles = []
    ul = soup.find("ul", class_="doc_list")
    if not ul:
        return []

    for li in ul.find_all("li", class_="odd"):
        a = li.find("a", href=True)
        if not a:
            continue
        href = a["href"]
        if not href:
            continue

        # Title from title attribute (complete)
        title = a.get("title", "") or a.get_text(strip=True)
        if not title or len(title) < 5:
            continue

        # Full URL (href is relative: ./202605/t20260531_4008117.shtml)
        if href.startswith("/"):
            full_url = BASE_URL + href
        elif href.startswith("http"):
            full_url = href
        else:
            full_url = urljoin(f"{BASE_URL}{LIST_PATH}/", href)

        # Date
        date_span = li.find("span", class_="date")
        date = date_span.get_text(strip=True) if date_span else ""

        articles.append((title, full_url, date))

    return articles


# ---------- DB ----------

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


def save_article(conn, title, page_url, publish_date, content, attachments):
    summary = content[:200] if content else title
    summary = re.sub(r"\s+", " ", summary).strip()
    att_json = json.dumps(attachments, ensure_ascii=False) if attachments else "[]"
    for attempt in range(3):
        try:
            cur = conn.execute(
                """INSERT OR IGNORE INTO gov_raw
                   (site_name, source_url, page_url, title, publish_date, summary, content, category, attachments, group_name)
                   VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)""",
                (SITE_NAME, page_url, page_url, title.strip(), publish_date,
                 summary, content, CATEGORY, att_json, GROUP),
            )
            conn.commit()
            return cur.rowcount > 0
        except sqlite3.OperationalError as e:
            if "locked" in str(e) and attempt < 2:
                time.sleep(2)
                continue
            print(f"  DB error: {e}", file=sys.stderr)
            return False
    return False


# ---------- Main ----------

def main():
    max_pages = MAX_PAGES
    if len(sys.argv) > 1:
        try:
            max_pages = int(sys.argv[1])
        except ValueError:
            if sys.argv[1] in ("--max-pages",):
                if len(sys.argv) > 2:
                    try:
                        max_pages = int(sys.argv[2])
                    except ValueError:
                        pass

    print(f"Scraping {SITE_NAME}, max pages: {max_pages}")

    conn = init_db()
    total_new = 0
    total_found = 0

    for pn in range(1, max_pages + 1):
        articles = extract_list_page(pn)
        if not articles:
            print(f"  Page {pn}: 0 articles (end)")
            break

        total_found += len(articles)

        for title, page_url, date in articles:
            if date and date < "2020-01-01":
                continue

            cur = conn.execute("SELECT id FROM gov_raw WHERE page_url = ?", (page_url,))
            if cur.fetchone():
                continue

            det_title, det_date, det_content, det_atts = fetch_detail(page_url, title)
            final_title = det_title or title
            final_date = det_date or date
            final_content = det_content or f"[{final_title}]({page_url})"
            final_atts = det_atts or []

            if save_article(conn, final_title, page_url, final_date, final_content, final_atts):
                total_new += 1

            time.sleep(0.3)

        print(f"  Page {pn}: {len(articles)} found, {total_new} new so far")

    conn.commit()
    conn.close()
    print(f"\nDone! Total found: {total_found}, New: {total_new}")


if __name__ == "__main__":
    main()
