#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# 准格尔旗 - 民意征集（社会稳定风险评估公示）
# CMS: 自制CMS
# List: index.html + index_{N}.html (3 pages, 10/page, ~25 total)
# Content: div.TRS_Editor

import requests
import re
import sqlite3
from bs4 import BeautifulSoup
from datetime import datetime

BASE_URL = "https://www.zge.gov.cn/zmhd1/myzj"
HEADERS = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36"
}
DB_PATH = "/root/search.db"
MAX_PAGES = 3  # Only 3 pages total

def get_pages():
    """Get all article URLs from list pages"""
    articles = []
    for page_num in range(MAX_PAGES):
        if page_num == 0:
            url = f"{BASE_URL}/index.html"
        else:
            url = f"{BASE_URL}/index_{page_num}.html"
        
        try:
            r = requests.get(url, headers=HEADERS, verify=False, timeout=30)
            r.encoding = "utf-8"
            if r.status_code != 200:
                continue
            
            soup = BeautifulSoup(r.text, "html.parser")
            div = soup.find("div", class_="yjzj_list")
            if not div:
                continue
            
            count = 0
            for li in div.find_all("li"):
                a = li.find("a")
                if a:
                    href = a.get("href", "")
                    title = a.get_text(strip=True)
                    if href and title:
                        if href.startswith("./"):
                            full_url = BASE_URL + href[1:]
                        elif href.startswith("/"):
                            full_url = "https://www.zge.gov.cn" + href
                        else:
                            full_url = BASE_URL + "/" + href
                        
                        # Extract date from text (征集时间：YYYY-MM-DD 至 YYYY-MM-DD)
                        li_text = li.get_text()
                        date_match = re.search(r"(\d{4}[-/]\d{2}[-/]\d{2})", li_text)
                        date_str = date_match.group(1) if date_match else ""
                        
                        articles.append({
                            "url": full_url,
                            "title": title,
                            "date": date_str
                        })
                        count += 1
            
            print(f"  [OK] Page {page_num+1}: {count} items")
            
        except Exception as e:
            print(f"  [ERR] Page {page_num+1}: {e}")
    
    return articles

def get_detail(url):
    """Fetch detail page and extract content and date"""
    try:
        r = requests.get(url, headers=HEADERS, verify=False, timeout=30)
        r.encoding = "utf-8"
        if r.status_code != 200 or len(r.text) < 1000:
            return None, None
        
        soup = BeautifulSoup(r.text, "html.parser")
        
        # Content: TRS_Editor (primary)
        content = None
        div = soup.find("div", class_="TRS_Editor")
        if div:
            content = "".join(str(tag) for tag in div.contents).strip()
        
        # Fallback: trs_editor or Detail_text
        if not content:
            for cls in ["trs_editor", "Detail_text"]:
                div = soup.find("div", class_=cls)
                if div:
                    content = "".join(str(tag) for tag in div.contents).strip()
                    break
        
        if not content:
            return None, None
        
        text_only = re.sub(r'<[^>]+>', '', content).strip()
        if len(text_only) < 50:
            return None, None
        
        # Date from PubDate meta
        pub_date = ""
        meta = soup.find("meta", attrs={"name": "PubDate"})
        if meta and meta.get("content"):
            pub_date = meta["content"].strip()[:10]
        
        return content, pub_date
    
    except Exception as e:
        print(f"  [ERR] {url[:80]}: {e}")
        return None, None

def main():
    print("=" * 60)
    print("准格尔旗 - 民意征集 爬虫")
    print(f"启动时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
    print("=" * 60)
    
    print("\n[1/3] 抓取列表页...")
    articles = get_pages()
    print(f"  共找到 {len(articles)} 条记录")
    
    if not articles:
        return
    
    print("\n[2/3] 检查数据库去重...")
    conn = sqlite3.connect(DB_PATH, timeout=60)
    c = conn.cursor()
    
    c.execute("SELECT page_url FROM gov_raw")
    existing = set(row[0] for row in c.fetchall())
    
    new_articles = [a for a in articles if a["url"] not in existing]
    print(f"  新增: {len(new_articles)}/{len(articles)}")
    
    if not new_articles:
        print("  没有新记录")
        conn.close()
        return
    
    print("\n[3/3] 抓取详情页...")
    imported = 0
    skipped = 0
    
    for i, article in enumerate(new_articles, 1):
        title_short = article["title"][:50].replace("\n", " ")
        print(f"  [{i}/{len(new_articles)}] {title_short}...", end=" ", flush=True)
        
        content, pub_date = get_detail(article["url"])
        
        if not content:
            print("✗ 无正文")
            skipped += 1
            continue
        
        date = pub_date or article["date"]
        
        text_only = re.sub(r'<[^>]+>', '', content).strip()
        summary = text_only[:200]
        
        try:
            c.execute("""INSERT OR IGNORE INTO gov_raw 
                (title, content, page_url, summary, site_name, publish_date, category)
                VALUES (?, ?, ?, ?, ?, ?, ?)""",
                (article["title"], content, article["url"], summary,
                 "准格尔旗", date, "环评公示"))
            if c.rowcount > 0:
                conn.commit()
                imported += 1
                print(f"✓ ({len(text_only)}字)")
            else:
                print("• 已存在")
        except Exception as e:
            print(f"✗ DB错误: {e}")
            conn.rollback()
    
    conn.close()
    print(f"\n{'=' * 60}")
    print(f"导入完成: {imported} 条 (跳过 {skipped} 条)")
    print(f"{'=' * 60}")

if __name__ == "__main__":
    main()
