#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Crawler for 钦北区人民政府 - 意见征集 (qinbei.gov.cn)
CMS: TRS/Hanweb
List: div#morelist > ul.more-list > li > span (date) + a[href][title]
Pagination: index.shtml (p1), index_1.shtml (p2), 30/page, 2 pages ~58 items
Detail: div.article > h1 (title), div.article-inf-left (date), div.article > div.article-content (or plain text after h1+inf)
         Table support: extract <table> as HTML for search_app

Usage:
    python3 /root/gov_crawler/crawl_qinbei_yjzj.py
"""

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.qinbei.gov.cn"
LIST_PATH = "/zmhd/yjzj"
TOTAL_PAGES = 2

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


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

def get_list_url(page_num):
    if page_num == 1:
        return f"{BASE_URL}{LIST_PATH}/index.shtml"
    return f"{BASE_URL}{LIST_PATH}/index_{page_num - 1}.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 []

    soup = BeautifulSoup(r.text, "html.parser")
    more = soup.select_one("div#morelist ul.more-list")
    if not more:
        return []

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

        href = a["href"].strip()
        title = a.get("title", "").strip() or a.get_text(strip=True)
        # Trim trailing "..." from list truncation
        if title.endswith("..."):
            title = title[:-3].strip()
        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


# ---------- 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 ---
    title = ""
    h1 = soup.select_one("div.article h1")
    if h1:
        title = h1.get_text(strip=True)
    if not title:
        t = soup.find("title")
        if t:
            title = t.get_text(strip=True).replace("钦北区人民政府", "").replace("- 意见征集", "").strip().rstrip("_- ")

    # --- Date ---
    date_str = ""
    info = soup.select_one("div.article-inf-left")
    if info:
        txt = info.get_text(strip=True)
        m = re.search(r"(\d{4}-\d{2}-\d{2})", txt)
        if m:
            date_str = m.group(1)

    # --- Content ---
    article = soup.find("div", class_="article")
    content = ""
    if article:
        # Remove h1 and info div to get content area
        for s in article.find_all(["script", "style"]):
            s.decompose()
        # Try to find a dedicated content div
        content_div = article.find("div", class_=["article-content", "content", "TRS_Editor"])
        if content_div:
            parts = []
            for el in content_div.find_all(["p", "table"]):
                if el.name == "table":
                    parts.append(str(el))
                elif not el.find_parent("table"):
                    t = el.get_text(strip=True)
                    if t:
                        parts.append(t)
            content = "\n\n".join(parts)
        else:
            # Fallback: grab all text after h1 and inf div
            parts = []
            for el in article.find_all(["p", "table"]):
                # Skip elements inside h1 or info div
                if el.find_parent("h1") or el.find_parent("div", class_="article-inf"):
                    continue
                if el.name == "table":
                    parts.append(str(el))
                elif not el.find_parent("table"):
                    t = el.get_text(strip=True)
                    if t:
                        parts.append(t)
            content = "\n\n".join(parts)

    # --- Attachments ---
    attachments = []
    seen = set()
    for a_tag in soup.find_all("a", href=True):
        href = a_tag["href"]
        if re.search(r"\.(pdf|doc|docx|xls|xlsx|rar|zip|txt)$", href, re.I):
            full_url = urljoin(url, href)
            name = a_tag.get_text(strip=True) or href.split("/")[-1].split("?")[0]
            if full_url not in seen:
                seen.add(full_url)
                attachments.append({"name": name, "url": full_url})
                if content:
                    content += f'\n\n附件：<p><a href="{full_url}">{name}</a></p>'

    return title, date_str, content, attachments


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

def with_retry(fn, desc="DB op", max_attempts=10, delay=5):
    for attempt in range(1, max_attempts + 1):
        try:
            return fn()
        except sqlite3.OperationalError as e:
            if "locked" in str(e) and attempt < max_attempts:
                print(f"  {desc}: locked (attempt {attempt}/{max_attempts}), retry in {delay}s...", file=sys.stderr)
                time.sleep(delay)
            else:
                print(f"  {desc} failed: {e}", file=sys.stderr)
                return False
    return False


def init_db():
    conn = sqlite3.connect(DB_PATH, timeout=30)
    conn.execute("PRAGMA journal_mode=WAL")
    conn.execute("PRAGMA busy_timeout=30000")
    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 "[]"
    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 = TOTAL_PAGES
    if len(sys.argv) > 1:
        try:
            max_pages = int(sys.argv[1])
        except ValueError:
            if sys.argv[1] in ("--max-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

    def do_clean():
# QC20260925 去掉整站清空再重灌(抢锁+中途死掉会清空整站; page_url 有 UNIQUE 索引，插入本就幂等)         conn.execute("DELETE FROM gov_raw WHERE site_name = ?", (SITE_NAME,))
        conn.commit()
    with_retry(do_clean, desc=f"Clean {SITE_NAME}")
    print(f"  Cleaned old data for {SITE_NAME}", file=sys.stderr)

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

        total_found += len(articles)

        for title, page_url, date in articles:
            if date and date < "2016-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)
            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.5)

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

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


if __name__ == "__main__":
    main()
