#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Crawler for 祁县人民政府 - 通知公告 (qixian.gov.cn)
CMS: 自定义 ASP.NET MVC
WAF: Baidu Yunjiasu - bypass using IP + Host header
List: ul.newsList > li > a[href] + span (date)
Pagination: /xwzx/tzgs_N (N=1-47), 20/page, 924 total
Detail: div.printArea > div.conTxt > p (paragraphs)
         Title: <title> (strip suffix)
         Date: div.property > span "发布时间：YYYY-MM-DD"

Usage:
    python3 /root/gov_crawler/crawl_qixian_tzgs.py             # Full crawl
    python3 /root/gov_crawler/crawl_qixian_tzgs.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_DOMAIN = "www.qixian.gov.cn"
BASE_IP = "218.26.234.201"
LIST_PATH = "/xwzx/tzgs"
TOTAL_PAGES = 47

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",
    "Host": BASE_DOMAIN,
}


def build_url(path):
    """Build URL using IP bypass for WAF"""
    return f"http://{BASE_IP}{path}"


def fetch_url(path):
    """Fetch a URL with WAF bypass"""
    url = build_url(path)
    try:
        r = requests.get(url, headers=HEADERS, timeout=20)
        r.encoding = "utf-8"
        return r
    except Exception as e:
        print(f"  Error fetching {path}: {e}", file=sys.stderr)
        return None


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

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

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

    # --- Title ---
    title = ""
    t = soup.find("title")
    if t:
        title = t.get_text(strip=True)
        # Clean suffix: "标题_通知公告_新闻中心_祁县人民政府"
        title = re.sub(r"_[^_]+_[^_]+_[^_]+$", "", title)

    # --- Date ---
    date_str = ""
    prop = soup.find("div", class_="property")
    if prop:
        for span in prop.find_all("span"):
            txt = span.get_text(strip=True)
            m = re.search(r"(\d{4}-\d{2}-\d{2})", txt)
            if m:
                date_str = m.group(1)
                break

    # --- Content ---
    pa = soup.find("div", class_="printArea")
    content = ""
    attachments = []

    if pa:
        # Remove scripts/styles
        for s in pa.find_all(["script", "style"]):
            s.decompose()

        con_txt = pa.find("div", class_="conTxt")
        if con_txt:
            parts = []
            for p in con_txt.find_all("p"):
                t = p.get_text(strip=True)
                if t:
                    parts.append(t)
            content = "\n\n".join(parts)

    # --- Attachments ---
    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(f"http://{BASE_DOMAIN}", href)
            name = a.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


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

def extract_list_page(page_num):
    if page_num == 1:
        path = LIST_PATH
    else:
        path = f"{LIST_PATH}_{page_num}"

    r = fetch_url(path)
    if not r or r.status_code != 200:
        return []

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

    items = []
    for li in ul.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)
        page_url = urljoin(f"http://{BASE_DOMAIN}", href)
        date_str = span.get_text(strip=True) if span else ""
        # Date format: YYYY-MM-DD
        date_str = re.sub(r"\s+", "", date_str)[:10]

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

    return items


# ---------- 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

    # Clean old data
    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 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

            # Check if exists
            cur = conn.execute("SELECT id FROM gov_raw WHERE page_url = ?", (page_url,))
            if cur.fetchone():
                continue

            # Extract detail path from page_url
            if f"http://{BASE_DOMAIN}" in page_url:
                detail_path = page_url.replace(f"http://{BASE_DOMAIN}", "")
            else:
                detail_path = ""
            if detail_path:
                det_title, det_date, det_content, det_atts = fetch_detail(detail_path)
            else:
                det_title, det_date, det_content, det_atts = title, date, "", []
            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()
