#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Crawler for 平罗县人民政府 - 公示公告 (pingluo.gov.cn)
CMS: TRS CMS
List: div.gl-list-con.newslist.gl-w75 > li > a[href][title] + span(date MM-DD)
Pagination: createPageHTML(28, 0, "index", "html") → index.html, index_N.html
Detail: div.view.TRS_UEDITOR trs_paper_default > p content
Title: meta ArticleTitle (clean 【公示公告】prefix)
Date: meta PubDate
Attachments: div.enclosure#fj > a[href*=./P0]

Usage:
    python3 /root/gov_crawler/crawl_pingluo_gsgg.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 = "https://www.pingluo.gov.cn"
LIST_DIR = "/xwzx/gsgg"
TOTAL_PAGES = 28

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


def fetch(url, retries=3):
    for i in range(retries):
        try:
            r = requests.get(url, headers=HEADERS, timeout=30)
            r.encoding = "utf-8"
            return r.text
        except Exception as e:
            if i < retries - 1:
                time.sleep(2)
            else:
                print(f"  [WARN] Failed to fetch {url}: {e}", file=sys.stderr)
                return None
    return None


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

def get_list_url(page_num):
    if page_num == 1:
        return f"{BASE_URL}{LIST_DIR}/index.html"
    return f"{BASE_URL}{LIST_DIR}/index_{page_num}.html"


def extract_list_page(page_num):
    url = get_list_url(page_num)
    html = fetch(url)
    if not html:
        return []

    soup = BeautifulSoup(html, "html.parser")
    items = []

    list_div = soup.find("div", class_="gl-list-con newslist gl-w75")
    if not list_div:
        return []

    for li in list_div.find_all("li", recursive=False):
        a = li.find("a", href=True)
        if not a:
            continue
        href = a["href"]
        page_url = urljoin(url, href)
        title = a.get("title", "").strip() or a.get_text(strip=True)
        if not title:
            continue
        span = li.find("span")
        date_str = span.get_text(strip=True) if span else ""
        items.append((title, page_url, date_str))

    return items


def normalize_date(list_date, page_url):
    """List date is MM-DD, extract year from URL path"""
    if not list_date:
        return ""
    # Try to get year from URL: /202607/t20260710_...
    m = re.search(r'/(20\d{2})\d{2}/', page_url)
    if m:
        year = m.group(1)
        return f"{year}-{list_date}"
    return list_date


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

def fetch_detail(url):
    html = fetch(url)
    if not html:
        return None, None, None, []

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

    # --- Title ---
    title = ""
    meta_title = soup.find("meta", attrs={"name": "ArticleTitle"})
    if meta_title and meta_title.get("content"):
        title = meta_title["content"].strip()
        # Clean 【公示公告】 prefix
        title = re.sub(r'^【[^】]*】\s*', '', title)
    if not title:
        t = soup.find("title")
        if t:
            title = t.get_text(strip=True).split("_")[0].strip()

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

    # --- Content ---
    content = ""
    editor = soup.find("div", class_=re.compile(r"TRS_UEDITOR"))
    if editor:
        for s in editor.find_all(["script", "style"]):
            s.decompose()
        parts = []
        for p in editor.find_all("p"):
            t = p.get_text(strip=True)
            if t and t not in (" ", "\xa0", "&nbsp;"):
                parts.append(t)
        for tbl in editor.find_all("table"):
            if not tbl.find_parent("table"):
                parts.append(str(tbl))
        content = "\n\n".join(parts)
    content = re.sub(r"\n{3,}", "\n\n", content).strip()

    # --- Attachments (from enclosure div and JS variable) ---
    attachments = []
    seen = set()

    # Try enclosure div
    enc_div = soup.find("div", class_="enclosure")
    if enc_div:
        for a_tag in enc_div.find_all("a", href=True):
            href = a_tag["href"]
            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})

    # Also check all links for file extensions
    for a_tag in soup.find_all("a", href=True):
        href = a_tag["href"]
        if re.search(r"\.(xls|xlsx|pdf|doc|docx|rar|zip)$", 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})

    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:
            pass

    print(f"Scraping {SITE_NAME}, max pages: {max_pages}", file=sys.stderr)
    conn = init_db()
    total_new = 0
    total_found = 0
    start_time = time.time()

    def do_clean():
# QC20260925 去掉整站清空再重灌(抢锁+中途死掉会清空整站; page_url 有 UNIQUE 索引，插入本就幂等)         conn.execute("DELETE FROM gov_raw WHERE site_name = ?", (SITE_NAME,))
        conn.commit()
    print("  Cleaning old data...", file=sys.stderr)
    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)
        batch_new = 0

        for title, page_url, date in articles:
            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 normalize_date(date, page_url)
            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
                batch_new += 1

            time.sleep(0.3)

        elapsed = int(time.time() - start_time)
        pages_left = max_pages - pn
        eta = int(pages_left / max(1, pn / max(1, elapsed)) / 60) if elapsed > 0 and pn > 0 else 0

        print(f"  Page {pn}/{max_pages}: +{batch_new} new, "
              f"{total_new}/{total_found} total, "
              f"{elapsed//60}:{elapsed%60:02d} elapsed, "
              f"ETA {eta}min", file=sys.stderr)

        if pn % 10 == 0:
            conn.commit()

    conn.commit()
    elapsed = int(time.time() - start_time)
    conn.close()
    print(f"\nDone! Found: {total_found}, New: {total_new}, Time: {elapsed//60}m{elapsed%60:02d}s", file=sys.stderr)


if __name__ == "__main__":
    main()
