#!/usr/bin/env python3
"""兴仁市人民政府-环境保护 (gzxr.gov.cn) 爬虫

CMS: TRS (拓尔思)
列表: /zfxxgk/fdzdgknr/zdmsxx/hjbh/index.html (静态分页: index_N.html)
详情: h1标题 + div.trs_editor_view正文 + meta PubDate日期
"""

import os, sqlite3, re, time, requests, sys
from bs4 import BeautifulSoup
from datetime import datetime, timezone, timedelta
from urllib3 import disable_warnings, exceptions
from concurrent.futures import ThreadPoolExecutor, as_completed
disable_warnings(exceptions.InsecureRequestWarning)

SITE_NAME = "兴仁市-环境保护"
BASE = "https://www.gzxr.gov.cn"
LIST_TPL = "https://www.gzxr.gov.cn/zfxxgk/fdzdgknr/zdmsxx/hjbh/index.html"
LIST_PAGE_TPL = "https://www.gzxr.gov.cn/zfxxgk/fdzdgknr/zdmsxx/hjbh/index_%d.html"
DB_PATH = os.environ.get("DB_PATH", "/root/search.db")
CUTOFF = (datetime.now(timezone.utc) - timedelta(days=365*3)).strftime("%Y-%m-%d")
HEADERS = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36"}
MAX_PAGES = 52
MAX_WORKERS = 6

def fetch(url, max_retry=3):
    for att in range(max_retry):
        try:
            r = requests.get(url, headers=HEADERS, timeout=20, verify=False)
            r.encoding = "utf-8"
            if r.status_code == 200:
                return r.text
        except Exception as e:
            if att < max_retry - 1:
                time.sleep(2)
    return None

def parse_list_page(html):
    items = []
    # Find all item links
    for m in re.finditer(r'<a[^>]*href="(https?://www\.gzxr\.gov\.cn[^"]*tj?\d+[^"]*\.html)"[^>]*title="([^"]*)"', html):
        url = m.group(1)
        title = m.group(2).strip()
        # Find date - look backward for a date pattern
        before = html[max(0,m.start()-300):m.start()].replace("\n"," ")
        date_m = re.search(r'(\d{4}[-/]\d{2}[-/]\d{2})', before)
        date_str = date_m.group(1).replace("/", "-") if date_m else ""
        if date_str and date_str < CUTOFF:
            continue
        items.append({"title": title, "url": url, "pub_date": date_str})
    return items

def fetch_detail(url):
    html = fetch(url)
    if not html:
        return "", "", ""
    
    # Title from h1
    title = ""
    m = re.search(r'<h1[^>]*>(.*?)</h1>', html)
    if m:
        title = re.sub(r'<[^>]+>', '', m.group(1)).strip()
    if not title:
        m = re.search(r'<title>(.*?)</title>', html)
        if m:
            title = m.group(1).strip()
    
    # Content from TRS editor — 2026-08-13 修复: 用BeautifulSoup完整提取
    # (原正则 (.*?)</div> 非贪婪, 正文含嵌套div时在第一个</div>处截断, 如 金矿公示 只取到208字符)
    content = ""
    _zsoup = BeautifulSoup(html, 'html.parser')
    _zel = _zsoup.find('div', id='Zoom') or _zsoup.select_one('div.trs_editor_view') or _zsoup.find('font', id='Zoom')
    if _zel:
        content = ''.join(str(c) for c in _zel.contents).strip()
    
    content = re.sub(r'<script[^>]*>.*?</script>', '', content, flags=re.S)
    content = re.sub(r'<style[^>]*>.*?</style>', '', content, flags=re.S)
    
    # Date
    date_str = ""
    m = re.search(r'<meta[^>]*name="PubDate"[^>]*content="(\d{4}-\d{2}-\d{2})', html)
    if m:
        date_str = m.group(1)
    if not date_str:
        m = re.search(r'发布时间[:\s]*(\d{4}[-/]\d{1,2}[-/]\d{1,2})', html)
        if m:
            date_str = m.group(1).replace("/", "-")
    if not date_str:
        m = re.search(r'(\d{4}-\d{1,2}-\d{1,2})', html)
        if m:
            date_str = m.group(1)
    
    return title, content, date_str

def main():
    test = "--test" in sys.argv
    mode = "TEST" if test else "FULL"
    print(f"\n=== {SITE_NAME} ({mode}) ===", flush=True)
    
    # Crawl list pages
    all_items = []
    for pg in range(1, MAX_PAGES + 1):
        url = LIST_TPL if pg == 1 else LIST_PAGE_TPL % pg
        html = fetch(url)
        if not html:
            print(f"  Page {pg}: fetch failed", flush=True)
            break
        items = parse_list_page(html)
        print(f"  Page {pg}: {len(items)} items", flush=True)
        all_items.extend(items)
        if len(items) == 0:
            break  # Empty page = end
    
    print(f"  Total: {len(all_items)} items within 3yr", flush=True)
    
    if not items:
        print("  No items to crawl")
        return
    
    if test:
        all_items = all_items[:3]
    
    # Fetch details
    conn = None if test else sqlite3.connect(DB_PATH, timeout=60)
    cursor = conn.cursor() if conn else None
    total_new = 0
    done = 0
    
    for i, item in enumerate(all_items):
        print(f"  [{i+1}/{len(all_items)}] {item['title'][:40]}... ", end="", flush=True)
        title, content, pub_date = fetch_detail(item["url"])
        if not title:
            title = item["title"]
        if not pub_date:
            pub_date = item["pub_date"]
        
        if test:
            print(f"title={title[:50]} content={len(content)}B date={pub_date}")
            continue
        
        try:
            cursor.execute(
                "INSERT OR IGNORE INTO gov_raw (site_name, title, page_url, content, publish_date, summary, tags) VALUES (?,?,?,?,?,?,?)",
                (SITE_NAME, title[:500], item["url"], content, pub_date, "", "环境保护"),
            )
            if cursor.rowcount > 0:
                total_new += 1
                print(f"{len(content)}B")
            else:
                print("skip")
        except Exception as e:
            print(f"DB error: {e}")
        
        done += 1
        if done % 30 == 0 and conn:
            conn.commit()
    
    if conn:
        conn.commit()
        conn.execute(
            "INSERT INTO gov_search(rowid, title, site_name, summary) "
            "SELECT r.rowid, r.title, r.site_name, r.summary "
            "FROM gov_raw r WHERE r.rowid NOT IN (SELECT rowid FROM gov_search) AND r.site_name=?",
            (SITE_NAME,)
        )
        conn.commit()
        c = conn.execute("SELECT COUNT(*) FROM gov_raw WHERE site_name=?", (SITE_NAME,))
        cnt = c.fetchone()[0]
        conn.close()
        print(f"\n=== 完成 ===", flush=True)
        print(f"  新增: {total_new}条", flush=True)
        print(f"  累计: {cnt}条", flush=True)

if __name__ == "__main__":
    main()
