#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""高昌区-公示公告 (TRS CMS, c105962)"""
import re, os, urllib.request, ssl
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 = "http://gcq.tlf.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"})
    resp = urllib.request.urlopen(req, timeout=30, context=ctx)
    return resp.read().decode("utf-8", errors="ignore")

def fetch_list(catid, page=1):
    if page == 1:
        url = "{}/gcq/c{}/zfxxgk_list.shtml".format(BASE, catid)
    else:
        url = "{}/gcq/c{}/zfxxgk_list_{}.shtml".format(BASE, catid, page)
    html = fetch(url)
    items = re.findall(
        r'<a[^>]*title="([^"]*)" href="([^"]+)"[^>]*>.*?</a>\s*<span>(\d{4}-\d{2}-\d{2})</span>',
        html, re.DOTALL
    )
    return items

def fetch_detail(url):
    full_url = url if url.startswith("http") else BASE + url
    html = fetch(full_url)
    
    # Title from UCAPTITLE
    m = re.search(r'<UCAPTITLE>\s*([^<]+?)\s*</UCAPTITLE>', html)
    title = m.group(1).strip() if m else ""
    if not title:
        m = re.search(r'<h3[^>]*>([^<]+)</h3>', html)
        title = m.group(1).strip() if m else ""
    
    # Content from vsb_content > v_news_content
    content = "正文为空"
    m = re.search(r'class="v_news_content"[^>]*>(.*?)</div>', html, re.DOTALL)
    if m:
        c = m.group(1).strip()
        if len(c) > 50:
            content = c
    
    if content == "正文为空":
        m = re.search(r'id="vsb_content"[^>]*>(.*?)</div>', html, re.DOTALL)
        if m:
            c = m.group(1).strip()
            if len(c) > 50:
                content = c
    
    if content != "正文为空":
        content = re.sub(r'<UCAPCONTENT>|</UCAPCONTENT>', '', content)
        content = re.sub(r'<script[^>]*>.*?</script>', '', content, flags=re.DOTALL)
        content = re.sub(r'<iframe[^>]*>.*?</iframe>', '', content, flags=re.DOTALL)
        content = content.strip()
        if not content: content = "正文为空"
    
    # Date
    date = ""
    m = re.search(r'发布时间[：:]\s*(\d{4}-\d{2}-\d{2})', html)
    if m: date = m.group(1)
    if not date:
        m = re.search(r'PubDate" content="(\d{4}-\d{2}-\d{2})', html)
        if m: date = m.group(1)
    
    # Clean title (remove UCAPTITLE tags)
    title = re.sub(r'<[^>]+>', '', title).strip()
    
    return title, date, content

def main():
    import sqlite3
    conn = sqlite3.connect(SEARCH_DB)
    cur = conn.cursor()
    conn.execute("PRAGMA journal_mode=WAL")
    
    catid = 105962
    total_pages = 46
    print("Total pages: {}".format(total_pages))
    total_new = 0
    total_skipped = 0
    
    for page in range(1, total_pages + 1):
        items = fetch_list(catid, page)
        if not items:
            print("  Page {}: no items found".format(page))
            continue
        
        page_new = 0
        for title, url, date in items:
            title = title.strip()
            if not title or not url:
                continue
            if date < CUTOFF:
                total_skipped += 1
                continue
            
            page_url = url if url.startswith("http") else BASE + url
            
            cur.execute("SELECT id FROM gov_raw WHERE page_url=?", (page_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, page_url, detail_title or title, pub_date or date, content, int(date.replace("-","")), "公示公告")
                )
                if cur.rowcount > 0:
                    total_new += 1
                    page_new += 1
                    print("  [{:4d}] {} | {}".format(total_new, title[:40], date))
                else:
                    total_skipped += 1
            except Exception as e:
                print("  [ERR] {}: {}".format(title[:30], str(e)[:50]))
                total_skipped += 1
        
        conn.commit()
        print("  P{}: {} new (total {})".format(page, page_new, total_new))
    
    conn.close()
    print("\n结果: {} 新增, {} 跳过".format(total_new, total_skipped))

if __name__ == "__main__":
    main()
