#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
江安县人民政府 - 通知公告 爬虫
CMS: TRS (TRS_UEDITOR)
List: /zwgk/jbxxgk/tzgg/index.html (P1), index_{N-1}.html(PN, N>=2)
Detail: /zwgk/jbxxgk/tzgg/YYYYMM/tYYYYMMDD_XXXXXXX.html
每页15条
"""

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 = "https://ybja.gov.cn"
LIST_PATH = "/zwgk/jbxxgk/tzgg"
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 = [
    "【打印本页】", "【关闭窗口】", "打印本页", "关闭窗口",
    "转载分享：", "浏览量：", "相关附件：", "相关稿件：",
    "扫一扫在手机打开", "附件：",
]


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

def render_paragraph(p_tag, detail_url):
    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):
    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"):
            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":
                    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)

    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)


def extract_attachments(soup):
    atts = []
    seen = set()
    # Look in attachment section first (fjxz, xgfj)
    for cls in ["fjxz", "xgfj"]:
        div = soup.find("div", class_=cls)
        if div:
            for a in div.find_all("a", href=True):
                href = a["href"]
                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})
    # Also search full page for file links
    if not atts:
        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


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:
        dt = soup.find("div", class_="doctitle")
        if dt:
            title = dt.get_text(strip=True)
    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_="doc_content")
    if not content_div:
        content_div = soup.find("div", class_="content")

    attachments = extract_attachments(soup)

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

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

    return title, date_str, content, attachments


def extract_list_page(page_num):
    if page_num == 1:
        url = f"{BASE_URL}{LIST_PATH}/index.html"
    else:
        url = f"{BASE_URL}{LIST_PATH}/index_{page_num - 1}.html"

    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_="list_content")
    if not ul:
        return []

    for li in ul.find_all("li", recursive=True):
        a = li.find("a", href=True)
        if not a:
            continue
        href = a["href"]
        if not href or href.startswith("#") or "javascript" in href:
            continue
        # Only include article links
        if not re.search(r"/t\d{8}_\d+\.html$", href) and not re.search(r"\d{6}/t\d{8}_", href):
            continue

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

        if href.startswith("/"):
            full_url = BASE_URL + href
        elif href.startswith("http"):
            full_url = href
        else:
            full_url = urljoin(url, href)

        date_span = li.find("span")
        date = date_span.get_text(strip=True) if date_span else ""

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

    return articles


def init_db():
    conn = sqlite3.connect(DB_PATH, timeout=60)
    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


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()
