#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Crawler for 岑巩县人民政府 - 通知公告 (qdncg.gov.cn)
CMS: TRS/UEDITOR
List: ul.NewsList > li > span(date) + a[href]
Pagination: index.html (p1), index_1.html (p2), ... index_88.html (p89), 15/page ~1332 items
Detail: div.ArticleTitle (title), div.trs_editor_view (content)
         Date from JS: var pubdata='YYYY-MM-DD HH:MM:SS'
         Attachments: a[appendix=true] or a[href*=./P0...]

Usage:
    python3 /root/gov_crawler/crawl_qdncg_tzgg.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.qdncg.gov.cn"
LIST_DIR = "/xwzx/tzgg"
TOTAL_PAGES = 89

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):
    """page_num is 1-indexed"""
    if page_num == 1:
        return f"{BASE_URL}{LIST_DIR}/"
    return f"{BASE_URL}{LIST_DIR}/index_{page_num-1}.html"


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"
        soup = BeautifulSoup(r.text, "html.parser")
    except Exception as e:
        print(f"  Error fetching {url}: {e}", file=sys.stderr)
        return []

    items = []
    # Find all article links in the page
    for a in soup.find_all("a", href=True):
        href = a["href"]
        # Only match links in the tzgg directory with article pattern
        if "tzgg" in href and href.endswith(".html") and "/t20" in href:
            page_url = urljoin(url, href)
            title = a.get("title", "").strip() or a.get_text(strip=True)
            if not title:
                continue
            # Get date from previous span sibling
            date_str = ""
            parent_li = a.parent
            if parent_li and parent_li.name == "li":
                span = parent_li.find("span")
                if span:
                    date_str = span.get_text(strip=True)
            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 = ""
    tit_div = soup.find("div", class_="ArticleTitle")
    if tit_div:
        title = tit_div.get_text(strip=True)
    if not title:
        t = soup.find("title")
        if t:
            title = t.get_text(strip=True).split("-")[0].strip()

    # --- Date (from JS var) ---
    date_str = ""
    # Match var pubdata='YYYY-MM-DD HH:MM:SS'
    m = re.search(r"var\s+pubdata\s*=\s*['\"]([^'\"]+)['\"]", r.text)
    if m:
        date_str = m.group(1)[:10]

    # --- Content ---
    editor = soup.find("div", class_="trs_editor_view")
    if not editor:
        zoom = soup.find("font", id="Zoom")
        if zoom:
            # Try nested trs_editor_view (newer articles), then first content div
            editor = zoom.find("div", class_=re.compile(r"trs_editor_view", re.I))
            if not editor:
                editor = zoom.find("div", recursive=False)
            if not editor:
                editor = zoom
    if not editor:
        editor = soup.find("div", class_="Article_Con")
    content = ""
    if editor:
        for s in editor.find_all(["script", "style"]):
            s.decompose()
        parts = []
        # Use direct child iteration to preserve document order
        for el in list(editor.children):
            if el.name is None:
                txt = el.strip()
                if txt:
                    parts.append(txt)
                continue
            tag = el.name.lower()
            if tag == "p":
                t = el.get_text(strip=True)
                if t and t not in (" ", " ", "&nbsp;"):
                    parts.append(t)
            elif tag == "table":
                parts.append(str(el))
            elif tag in ("div", "section"):
                # Check for table inside wrapper
                tbl = el.find("table", recursive=False)
                if tbl:
                    parts.append(str(tbl))
                else:
                    # Extract non-empty text from wrapper
                    txt = el.get_text(strip=True)
                    if txt:
                        parts.append(txt)
        content = "\n\n".join(parts)
    # Remove overlay/share text pollution
    content = re.sub(r"扫一扫在手机打开当前页面", "", content).strip()
    content = re.sub(r"\n{3,}", "\n\n", content).strip()

    # --- Attachments ---
    attachments = []
    seen = set()
    for a_tag in soup.find_all("a", href=True):
        href = a_tag["href"]
        # Check for attachment patterns
        is_attachment = (
            a_tag.get("appendix") == "true" or
            re.search(r"\.(pdf|doc|docx|xls|xlsx|rar|zip|txt)$", href, re.I) or
            href.startswith("./P0") or
            "/P0" in href
        )
        if is_attachment:
            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():
        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:
            if date and date < "2005-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
                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()
