#!/usr/bin/env python3
"""
宿城区-公告公示 爬虫 (UCAP CMS)
站点: www.sqsc.gov.cn
"""
import requests, re, sqlite3, time, sys
from bs4 import BeautifulSoup
import warnings
warnings.filterwarnings('ignore')
from datetime import datetime, timedelta
import os

SEARCH_DB = os.getenv("SEARCH_DB", "/root/search.db")
SITE_NAME = "宿城-公告公示"
DOMAIN = "www.sqsc.gov.cn"
BASE_PATH = "/scq/gggs"

CUTOFF = (datetime.now() - timedelta(days=3*365)).strftime("%Y-%m-%d")
HEADERS = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36"}


def fetch_list_page(page):
    if page == 1:
        url = f"http://{DOMAIN}{BASE_PATH}/list.shtml"
    else:
        url = f"http://{DOMAIN}{BASE_PATH}/list_{page}.shtml"

    for retry in range(3):
        try:
            r = requests.get(url, headers=HEADERS, timeout=30)
            if r.status_code == 200:
                r.encoding = "utf-8"
                soup = BeautifulSoup(r.text, 'html.parser')

                items = []
                pg = soup.find('div', class_='pageList')
                if not pg:
                    return [], 0
                ul = pg.find('ul')
                if not ul:
                    return [], 0

                for li in ul.find_all('li'):
                    a = li.find('a')
                    if not a:
                        continue
                    href = a.get('href', '').strip()
                    title = a.get('title', '') or a.get_text(strip=True)
                    span = li.find('span', class_='time')
                    date = span.get_text(strip=True) if span else ""

                    if not href.startswith('http'):
                        href = f"http://{DOMAIN}{href}" if href.startswith('/') else f"http://{DOMAIN}{BASE_PATH}/{href}"

                    items.append({"url": href, "title": title, "date": date})

                pm = re.search(r"createPageHTML\('page_div',\s*(\d+)", r.text)
                total_pages = int(pm.group(1)) if pm else 206
                return items, total_pages
        except Exception as e:
            if retry < 2:
                time.sleep(2)
    return [], 0


def extract_content(html):
    soup = BeautifulSoup(html, 'html.parser')
    zoom = soup.find('div', id='zoomcon')
    if zoom:
        for tag in zoom.find_all(['script', 'style']):
            tag.decompose()
        text = zoom.get_text(strip=True)
        if len(text) > 30:
            return str(zoom)
    ac = soup.find('div', class_='article-content')
    if ac:
        for tag in ac.find_all(['script', 'style']):
            tag.decompose()
        text = ac.get_text(strip=True)
        if len(text) > 30:
            return str(ac)
    return ""


def extract_meta(html):
    soup = BeautifulSoup(html, 'html.parser')
    title = ""
    tm = soup.find('meta', attrs={"name": "ArticleTitle"})
    if tm and tm.get('content'):
        title = tm['content'].strip()
    if not title:
        h1 = soup.find('h1', class_='article-title')
        if h1:
            title = h1.get_text(strip=True)
    if not title:
        tt = soup.find('title')
        if tt:
            title = tt.get_text(strip=True)
    date = ""
    pm = soup.find('meta', attrs={"name": "PubDate"})
    if pm and pm.get('content'):
        d = pm['content'].strip()
        cm = re.match(r'(\d{4})-(\d{1,2})-(\d{1,2})', d)
        if cm:
            date = f"{cm.group(1)}-{cm.group(2).zfill(2)}-{cm.group(3).zfill(2)}"
    if not date:
        dm = re.search(r'(\d{4}-\d{2}-\d{2})', html)
        if dm:
            date = dm.group(1)
    return title, date


def insert_article(url, title, date, content):
    db = sqlite3.connect(SEARCH_DB, timeout=60)
    db.execute("PRAGMA journal_mode=WAL")
    try:
        db.execute(
            "INSERT OR IGNORE INTO gov_raw(site_name,source_url,page_url,title,publish_date,content,summary,status,category) VALUES(?,?,?,?,?,?,?,?,?)",
            (SITE_NAME, url, url, title, date, content, title[:200], "active", "公告公示"))
        affected = db.total_changes
        db.commit()
        if affected:
            db.execute(
                "INSERT OR REPLACE INTO gov_search(rowid,title,site_name,summary) SELECT r.id,r.title,r.site_name,r.summary FROM gov_raw r WHERE r.page_url=? AND r.id NOT IN (SELECT rowid FROM gov_search)",
                (url,))
            db.commit()
        db.close()
        return affected
    except Exception as e:
        db.close()
        print(f"  DB error: {e}")
        return 0


def run(max_pages=210):
    print(f"\n{'='*50}")
    print(f"🚀 {SITE_NAME}")
    print(f"{'='*50}")

    items, total_pages = fetch_list_page(1)
    if not items:
        print("❌ 列表页无数据")
        return

    total_pages = min(max_pages, total_pages)
    print(f"  共{total_pages}页, 约2469条")

    all_items = list(items)
    for pg in range(2, total_pages + 1):
        its, _ = fetch_list_page(pg)
        if not its:
            break
        all_items.extend(its)
        dates = [it["date"] for it in its if it["date"]]
        if dates:
            print(f"  第{pg}页: {len(its)} 条 ({min(dates)} ~ {max(dates)})")
        else:
            print(f"  第{pg}页: {len(its)} 条")
        time.sleep(0.2)

    print(f"\n📊 共 {len(all_items)} 条")
    new = skip = no_body = err = 0
    for i, item in enumerate(all_items, 1):
        if item["date"] and item["date"] < CUTOFF:
            skip += 1
            continue
        for retry in range(3):
            try:
                r = requests.get(item["url"], headers=HEADERS, timeout=30)
                if r.status_code == 200:
                    r.encoding = "utf-8"
                    html = r.text
                    break
            except:
                if retry < 2:
                    time.sleep(2)
                html = None
        if not html:
            err += 1
            continue
        pt, pd = extract_meta(html)
        real_title = pt if pt else item["title"]
        real_date = pd if pd else item["date"]
        if real_date and real_date < CUTOFF:
            skip += 1
            continue
        content = extract_content(html)
        text_len = len(re.sub(r'<[^>]+>', '', content).strip()) if content else 0
        if text_len < 10:
            no_body += 1
            continue
        if insert_article(item["url"], real_title, real_date, content):
            new += 1
        else:
            skip += 1
        if i % 5 == 0:
            print(f"  ...{i}/{len(all_items)}")
        time.sleep(0.2)

    print(f"\n📊 FTS同步...")
    db = sqlite3.connect(SEARCH_DB, timeout=60)
    # QC20260926 去掉手写 gov_search 整站删除(抢锁源; FTS 由 gov_raw 触发器维护) 
    # db.execute("DELETE FROM gov_search WHERE site_name=?", (SITE_NAME,))
    db.execute("INSERT OR REPLACE INTO gov_search(rowid,title,site_name,summary) SELECT rowid,title,site_name,summary FROM gov_raw WHERE site_name=?", (SITE_NAME,))
    db.commit()
    c = db.execute("SELECT COUNT(*) FROM gov_search WHERE site_name=?", (SITE_NAME,))
    cnt = c.fetchone()[0]
    db.close()
    print(f"  FTS: {cnt} 条")
    print(f"\n✅ {SITE_NAME}: 新增{new}, 跳过{skip}, 空正文{no_body}, 错误{err}, FTS共{cnt}条")


if __name__ == "__main__":
    mp = int(sys.argv[1]) if len(sys.argv) > 1 else 210
    run(mp)
