#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Crawler for 上饶经济技术开发区 - 公告公示
CMS: UCAPCONTENT inside #zoomcon (custom CMS by 汉通科技)
List: <ul id="doclist"><li><a href="..." title="完整标题">标题(截断)</a><span>日期</span></li>
Pagination: zfxxgk.shtml (page1), zfxxgk_{N}.shtml (page N), 20/page, ~50 pages

Usage:
    python3 crawl_srkfq_gggs.py             # Full crawl (up to 50 pages)
    python3 crawl_srkfq_gggs.py --max-pages 1  # Incremental
"""

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

DB_PATH = "/root/search.db"
SITE_NAME = "上饶经济技术开发区-公告公示"
CATEGORY = "通知公告"
GROUP = "江西"
BASE_URL = "http://www.srkfq.gov.cn"
LIST_URL = "http://www.srkfq.gov.cn/srkfq/035/zfxxgk.shtml"
MAX_PAGES = 50  # 50 pages × 20 items = 1000 records

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


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


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

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)
                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)
                parts.append(f"![{alt}]({full_src})" if alt else f"![]({full_src})")
        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 from UCAPCONTENT or #zoomcon div."""
    parts = []
    processed = set()

    for s in content_div.find_all(["script", "style"]):
        s.decompose()

    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 and not any(sk in txt for sk in SKIP_TEXTS):
                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":
            if id(child) in processed:
                continue
            processed.add(id(child))
            src = child.get("src", "")
            if src:
                alt = child.get("alt", "")
                full_src = urljoin(detail_url, src)
                parts.append(f"![{alt}]({full_src})" if alt else f"![]({full_src})")

        elif tn in ("div", "section", "center", "ucapcontent"):
            for sub in child.find_all(["p", "table", "img", "span"], recursive=True):
                if id(sub) in processed:
                    continue
                processed.add(id(sub))
                if sub.name == "p":
                    # Skip <p> inside <table> (already handled by table_to_md)
                    if sub.find_parent("table"):
                        continue
                    txt = render_paragraph(sub, detail_url)
                    if txt and not any(sk in txt for sk in SKIP_TEXTS):
                        parts.append(txt)
                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)
                        parts.append(f"![{alt}]({full_src})" if alt else f"![]({full_src})")
                elif sub.name == "span":
                    # Skip spans inside <p> or <table> (already extracted by those handlers)
                    if sub.find_parent("p") or sub.find_parent("table"):
                        continue
                    txt = sub.get_text(" ", strip=True)
                    if txt and not any(sk in txt for sk in SKIP_TEXTS):
                        # Dedup: skip if already have same or longer text containing this one
                        is_dup = False
                        for i, existing in enumerate(parts):
                            if txt in existing and len(txt) <= len(existing):
                                is_dup = True
                                break
                            if existing in txt and len(existing) < len(txt):
                                parts[i] = txt
                                is_dup = True
                                break
                        if not is_dup:
                            parts.append(txt)

        else:
            # Inline elements (span, font, b, etc.) as direct children
            # Extract their rendered text, handling nested a/img
            txt = render_paragraph(child, detail_url)
            if txt and not any(sk in txt for sk in SKIP_TEXTS):
                parts.append(txt)

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


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

def extract_attachments(soup, detail_url):
    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):
            full_url = urljoin(detail_url, href)
            name = a.get_text(strip=True) or href.split("/")[-1].split("?")[0]
            if full_url not in seen:
                seen.add(full_url)
                atts.append({"name": name, "url": full_url})
    return atts


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

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

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

    # --- Title from Meta ---
    title = ""
    mt = soup.find("meta", attrs={"name": "ArticleTitle"})
    if mt and mt.get("content"):
        title = mt["content"].strip()
    if not title:
        tag = soup.find("title")
        if tag:
            t = tag.get_text(strip=True)
            t = re.sub(r"\s*[-_—|].*(?:公告公示|上饶经济技术开发区).*$", "", t).strip()
            title = t

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

    # --- Content (#zoomcon > UCAPCONTENT) ---
    content_div = soup.find("div", id="zoomcon")
    # Try UCAPCONTENT inside zoomcon
    if content_div:
        ucap = content_div.find("UCAPCONTENT")
        if ucap:
            content_div = ucap

    attachments = extract_attachments(soup, url)

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

    # Image-only fallback
    if len(content.strip()) < 20:
        content = f'<p><a href="{url}">{title}</a></p>'
        imgs = soup.find_all("img")
        img_lines = []
        for img in imgs:
            src = img.get("src", "")
            if src:
                full_src = urljoin(url, src)
                alt = img.get("alt", "")
                img_lines.append(f"![{alt}]({full_src})" if alt else f"![]({full_src})")
        if img_lines:
            content += "\n\n" + "\n\n".join(img_lines)

    if attachments:
        for a in attachments:
            content += f"\n\n附件：[{a['name']}]({a['url']})"

    return title, date_str, content, attachments


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

def get_list_url(page_num):
    if page_num == 1:
        return LIST_URL
    return f"http://www.srkfq.gov.cn/srkfq/035/zfxxgk_{page_num}.shtml"


def extract_list_page(page_num):
    url = get_list_url(page_num)
    try:
        r = requests.get(url, headers=HEADERS, timeout=20)
        r.encoding = "utf-8"
    except Exception as e:
        print(f"  Error fetching {url}: {e}", file=sys.stderr)
        return []

    if r.status_code != 200:
        print(f"  Page {page_num}: HTTP {r.status_code}", file=sys.stderr)
        return []

    soup = BeautifulSoup(r.text, "html.parser")
    doclist = soup.find("ul", id="doclist")
    if not doclist:
        return []

    items = []
    for li in doclist.find_all("li"):
        a = li.find("a")
        span = li.find("span")
        if not a or not a.get("href"):
            continue

        href = a["href"].strip()
        # Use title attribute for full title (link text is truncated)
        title = a.get("title", "").strip() or a.get_text(strip=True)
        page_url = urljoin(url, href)
        date_str = span.get_text(strip=True) if span else ""

        if title and page_url:
            items.append((title, page_url, date_str))

    return items


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

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 if content else title
    summary = re.sub(r"\s+", " ", summary).strip()
    att_json = json.dumps(attachments, ensure_ascii=False) if attachments else "[]"
    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),
        )
        return cur.rowcount > 0
    except Exception as e:
        print(f"  DB error: {e}", file=sys.stderr)
        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].startswith("--pages="):
                try:
                    max_pages = int(sys.argv[1].split("=")[1])
                except ValueError:
                    pass
            elif sys.argv[1] in ("--max-pages", "--pages") and len(sys.argv) > 2:
                try:
                    max_pages = int(sys.argv[2])
                except ValueError:
                    pass

    print(f"Scraping {SITE_NAME}, max pages: {max_pages}", file=sys.stderr)
    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)", file=sys.stderr)
            break

        total_found += len(articles)

        for title, page_url, date in articles:
            if date and date < "2020-01-01":
                print(f"  Skip old: {date} {title[:40]}", file=sys.stderr)
                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)
            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
                if total_new <= 5:
                    print(f"  + {final_date} {final_title[:50]}", file=sys.stderr)

            time.sleep(0.3)

        print(f"  Page {pn}: {len(articles)} found, {total_new} new", file=sys.stderr)

    conn.commit()
    conn.close()
    print(f"\nDone! Found: {total_found}, New: {total_new}", file=sys.stderr)


if __name__ == "__main__":
    main()
