#!/usr/bin/env python3
"""
鄂州市-环评审批公示 爬虫
站点: www.ezhou.gov.cn/gk/zdlyxxgk/hjbh_1852/hpspgs/
列表: 7页, 每页20条, 约140条
正文: <div class="TRS_Editor">
"""
import sys, os, re, time, json, sqlite3, urllib.request
from datetime import datetime, timedelta
import os

SEARCH_DB = os.getenv("SEARCH_DB", "/root/search.db")
BASE_URL = "https://www.ezhou.gov.cn/gk/zdlyxxgk/hjbh_1852/hpspgs"
SITE_NAME = "鄂州环评审批公示"
THREE_YEARS_AGO = datetime.now() - timedelta(days=3*365)
THREE_YEAR_LIMIT = True
MAX_PAGES = 5

HEADERS = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36"}

def save_to_db(records):
    db = sqlite3.connect(SEARCH_DB, timeout=60)
    try:
        for r in records:
            db.execute("INSERT OR IGNORE INTO gov_raw(title, content, publish_date, source_url, page_url, site_name) VALUES (?,?,?,?,?,?)",
                       (r['title'], r['content'], r['publish_date'], r['url'], r['url'], SITE_NAME))
        db.commit()
    finally:
        db.close()

def fetch_list_page(page):
    if page == 1:
        url = f"{BASE_URL}/index.html"
    else:
        url = f"{BASE_URL}/index_{page}.html"
    req = urllib.request.Request(url, headers=HEADERS)
    try:
        resp = urllib.request.urlopen(req, timeout=30)
        html = resp.read().decode('utf-8', errors='replace')
        return html
    except Exception as e:
        print(f"  \u26a0 第{page}页失败: {e}")
        return ""

def parse_list(html):
    items = []
    # Find all items inside the list div
    lis = re.findall(r'<li>(.*?)</li>', html, re.DOTALL)
    for li in lis:
        a = re.search(r'href=["\']([^"\']+)["\']', li)
        t = re.search(r'title=["\']([^"\']*)["\']', li)
        s = re.search(r'<span[^>]*>([^<]+)</span>', li)
        if a and t:
            url = a.group(1).strip()
            title = t.group(1).strip()
            date_str = s.group(1).strip() if s else ""
            items.append((url, title, date_str))
    return items

def fetch_detail(url):
    full_url = url if url.startswith('http') else f"https://www.ezhou.gov.cn{url}"
    if not url.startswith('http') and not url.startswith('/'):
        full_url = f"{BASE_URL}/{url}"
        full_url = full_url.replace("/./", "/")
    req = urllib.request.Request(full_url, headers=HEADERS)
    try:
        resp = urllib.request.urlopen(req, timeout=30)
        html = resp.read().decode('utf-8', errors='replace')
        content = ""
        m = re.search(r'class=["\']*TRS_Editor["\']*[^>]*>(.*?)</div>\s*</div>', html, re.DOTALL)
        if m:
            content = m.group(1).strip()
            # 移除 CSS style 块
            content = re.sub(r'<style[^>]*>.*?</style>', '', content, flags=re.DOTALL)
        return content
    except Exception as e:
        print(f"  \u26a0 详情失败: {full_url}: {e}")
        return ""

def main():
    print(f"{'='*50}")
    print(f"{SITE_NAME}")
    print(f"{'='*50}")
    
    all_articles = []
    all_urls = set()
    
    for page in range(1, MAX_PAGES + 1):
        html = fetch_list_page(page)
        if not html:
            continue
        items = parse_list(html)
        print(f"  \U0001f4c4 第{page}页: {len(items)}条", end="")
        for url, title, date_str in items:
            if url in all_urls:
                continue
            all_urls.add(url)
            if THREE_YEAR_LIMIT and date_str:
                try:
                    pub_date = datetime.strptime(date_str, '%Y-%m-%d')
                    if pub_date < THREE_YEARS_AGO:
                        continue
                except:
                    pass
            # Normalize URL
            if url.startswith('./'):
                full_url = f"{BASE_URL}/{url[2:]}"
            elif url.startswith('/'):
                full_url = f"https://www.ezhou.gov.cn{url}"
            else:
                full_url = f"{BASE_URL}/{url}"
                full_url = full_url.replace("/./", "/")
            all_articles.append({'url': full_url, 'title': title, 'publish_date': date_str})
        print(f" \u2192 累计{len(all_articles)}条")
    
    print(f"\n\U0001f4ca 列表总计: {len(all_articles)} 条")
    print(f"\n{'='*50}")
    print("抓取详情页...")
    
    batch = []
    total_saved = 0
    
    for i, art in enumerate(all_articles):
        title = art['title']
        print(f"  [{i+1}/{len(all_articles)}] {title[:50]}...", end=" ")
        
        content = fetch_detail(art['url'])
        if content:
            batch.append({
                'title': title,
                'content': content,
                'publish_date': art['publish_date'],
                'url': art['url']
            })
            print(f"\u2705 ({len(content)}字)")
            if len(batch) >= 10:
                save_to_db(batch)
                total_saved += len(batch)
                batch = []
        else:
            print("\u26a0 无正文")
    
    if batch:
        save_to_db(batch)
        total_saved += len(batch)
    
    print(f"\n{'='*50}")
    print(f"\u2705 完成! 入库: {total_saved}条")
    
    if total_saved > 0:
        db = sqlite3.connect(SEARCH_DB, timeout=60)
        try:
            db.execute("INSERT OR REPLACE INTO gov_search(rowid, title, site_name, summary) SELECT rowid, title, site_name, substr(content,1,200) FROM gov_raw WHERE site_name=? AND rowid NOT IN (SELECT rowid FROM gov_search WHERE site_name=?)", (SITE_NAME, SITE_NAME))
            db.commit()
            print("   FTS已更新")
        except Exception as e:
            print(f"   FTS更新: {e}")
        finally:
            db.close()

if __name__ == '__main__':
    main()
