#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""宣威市-公示公告 (Laravel分页, 自定义CMS)"""
import re, os, urllib.request, ssl, sqlite3
from datetime import datetime, timedelta

ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE

SEARCH_DB = os.getenv("SEARCH_DB", "/root/search.db")
SITE_NAME = "宣威市-公示公告"
BASE = "https://www.xw.gov.cn"
CUTOFF = (datetime.now() - timedelta(days=3*365)).strftime("%Y-%m-%d")

def fetch(url):
    req = urllib.request.Request(url, headers={"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36"})
    resp = urllib.request.urlopen(req, timeout=30, context=ctx)
    return resp.read().decode("utf-8", errors="ignore")

def fetch_list(page=1):
    if page == 1:
        url = BASE + "/gov/public/special/shx.html"
    else:
        url = BASE + "/gov/public/special/shx.html?page={}".format(page)
    html = fetch(url)
    items = []
    for m in re.finditer(
        r'<li><a href="(https?://www\.xw\.gov\.cn[^"]+)"[^>]*>([^<]+)</a>\s+(\d{4}-\d{2}-\d{2})</li>',
        html
    ):
        items.append((m.group(2).strip(), m.group(1), m.group(3)))
    return items

def fetch_detail(url):
    html = fetch(url)
    
    title = ""
    m = re.search(r'<h3 class="public_web_title">([^<]+)</h3>', html)
    if m: title = m.group(1).strip()
    if not title:
        m = re.search(r'<title>([^<]+)</title>', html)
        if m: title = m.group(1).strip()
    
    # Content from public_web_con des
    content = "正文为空"
    m = re.search(r'<div class="public_web_con des"[^>]*>(.*?)</div>\s*</div>', html, re.DOTALL)
    if m:
        c = m.group(1).strip()
        if len(c) > 50:
            content = c
    
    if content != "正文为空":
        content = re.sub(r'<script[^>]*>.*?</script>', '', content, flags=re.DOTALL)
        content = re.sub(r'<iframe[^>]*>.*?</iframe>', '', content, flags=re.DOTALL)
        content = re.sub(r'<style[^>]*>.*?</style>', '', content, flags=re.DOTALL)
        content = content.strip()
        if not content:
            content = "正文为空"
    
    # Date from article_attr .time
    date = ""
    m = re.search(r'<li class="time">(\d{4}-\d{2}-\d{2})', html)
    if m: date = m.group(1)
    if not date:
        m = re.search(r'(\d{4}-\d{2}-\d{2})\s+\d{2}:\d{2}', html)
        if m: date = m.group(1)
    
    title = re.sub(r'<[^>]+>', '', title).strip()
    return title, date, content

def main():
    conn = sqlite3.connect(SEARCH_DB)
    cur = conn.cursor()
    conn.execute("PRAGMA journal_mode=WAL")
    conn.execute("PRAGMA busy_timeout=10000")
    
    # Get total pages
    html = fetch(BASE + "/gov/public/special/shx.html")
    pages_m = re.findall(r'href="/gov/public/special/shx\.html\?page=(\d+)"', html)
    max_page = max(int(p) for p in pages_m) if pages_m else 1
    print("Total pages: {}".format(max_page))
    
    total_new = 0
    total_skipped = 0
    
    for page in range(1, max_page + 1):
        items = fetch_list(page)
        if not items:
            continue
        
        page_new = 0
        for title, url, date in items:
            if date < CUTOFF:
                total_skipped += 1
                continue
            
            cur.execute("SELECT id FROM gov_raw WHERE page_url=?", (url,))
            if cur.fetchone():
                total_skipped += 1
                continue
            
            try:
                detail_title, pub_date, content = fetch_detail(url)
                if content == "正文为空":
                    total_skipped += 1
                    continue
                
                cur.execute(
                    "INSERT OR IGNORE INTO gov_raw (site_name, page_url, title, publish_date, content, date_rank, category) VALUES (?,?,?,?,?,?,?)",
                    (SITE_NAME, url, detail_title or title, pub_date or date, content, int(date.replace("-", "")), "公示公告")
                )
                if cur.rowcount > 0:
                    total_new += 1
                    page_new += 1
            except Exception as e:
                print("  ERR: {} - {}".format(title[:30], str(e)[:60]))
                total_skipped += 1
        
        conn.commit()
        print("  Page {}: {} new (total {})".format(page, page_new, total_new))
    
    conn.close()
    print("\n结果: {} 新增, {} 跳过".format(total_new, total_skipped))

if __name__ == "__main__":
    main()
