#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""补爬高昌区-公示公告 (修复正则截断标题问题)"""
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 = "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)
    # 修复: 用 robust pattern (不用 backreference)
    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)
    m = re.search(r"<UCAPTITLE>\s*([^<]+?)\s*</UCAPTITLE>", html)
    title = m.group(1).strip() if m else ""
    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 = ""
    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)
    title = re.sub(r"<[^>]+>", "", title).strip()
    return title, date, content

def main():
    conn = sqlite3.connect(SEARCH_DB, timeout=60)
    cur = conn.cursor()
    conn.execute("PRAGMA journal_mode=WAL")
    catid = 105962
    total_new = 0
    for page in range(1, 47):
        items = fetch_list(catid, page)
        for title, url, date in items:
            title = title.strip()
            if not title or not url:
                continue
            if date < CUTOFF:
                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():
                continue
            try:
                detail_title, pub_date, content = fetch_detail(url)
                if content == "正文为空":
                    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
                    print("  NEW: {} | {}".format(title[:60], date))
            except Exception as e:
                print("  ERR: {} - {}".format(title[:30], str(e)[:60]))
        conn.commit()
        print("  Page {} done".format(page))
    conn.close()
    print("补爬结果: {} 条新增".format(total_new))

if __name__ == "__main__":
    main()
