#!/usr/bin/env python3
"""
东乡区-环境保护 爬虫 (Hanweb xxgk接口)
站点: www.jxfzdx.gov.cn/col/col21311/
列表: xxgk POST接口, infotypeId=L00004L00004L00010
"""
import sys, os, re, time, json, sqlite3, urllib.request, urllib.parse
from datetime import datetime, timedelta
import os

SEARCH_DB = os.getenv("SEARCH_DB", "/root/search.db")
API_URL = "https://www.jxfzdx.gov.cn/module/xxgk/search.jsp"
BASE = "https://www.jxfzdx.gov.cn"
SITE_NAME = "东乡环境保护"
THREE_YEARS_AGO = datetime.now() - timedelta(days=3*365)
THREE_YEAR_LIMIT = True

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_page(page):
    post_data = {
        "infotypeId": "L00004L00004L00010",
        "jdid": "53",
        "area": "",
        "divid": "div7299",
        "vc_title": "",
        "vc_number": "",
        "currpage": str(page)
    }
    data = urllib.parse.urlencode(post_data).encode('utf-8')
    req = urllib.request.Request(API_URL, data=data, headers=HEADERS)
    try:
        resp = urllib.request.urlopen(req, timeout=30)
        return resp.read().decode('utf-8', errors='replace')
    except Exception as e:
        print(f"  \u26a0 第{page}页失败: {e}")
        return ""

def parse_list(html):
    items = []
    for li in re.findall(r'<li>(.*?)</li>', html, re.DOTALL):
        ma = re.search(r'href=["\x27]([^"\x27]+)["\x27][^>]*title=["\x27]([^"\x27]*)["\x27]', li)
        md = re.search(r'(\d{4}-\d{2}-\d{2})', li)
        if ma:
            url = ma.group(1)
            title = ma.group(2).strip()
            date_str = md.group(1) if md else ""
            if url.startswith('/art/') or 'art_' in url:
                items.append((url, title, date_str))
    return items

def fetch_detail(url):
    full_url = url if url.startswith('http') else f"{BASE}{url}"
    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'ZJEG_RSS\.content\.begin-->(.*?)<!--ZJEG_RSS\.content\.end', html, re.DOTALL)
        if m:
            content = m.group(1).strip()
            content = re.sub(r'<meta[^>]*>', '', content)
        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}")
    
    # Get first page to find total
    html = fetch_page(1)
    if not html:
        return
    total_match = re.search(r'共(\d+)条', html)
    total_records = int(total_match.group(1)) if total_match else 0
    print(f"📊 总条数: {total_records}")
    
    per_page = 18
    total_pages = (total_records + per_page - 1) // per_page
    print(f"📄 总页数: {total_pages}")
    
    all_articles = []
    all_urls = set()
    
    for page in range(1, total_pages + 1):
        if page > 1:
            html = fetch_page(page)
            if not html:
                continue
        items = parse_list(html)
        print(f"  📄 第{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
            full_url = url if url.startswith('http') else f"{BASE}{url}"
            all_articles.append({'url': full_url, 'title': title, 'publish_date': date_str})
        print(f" → 累计{len(all_articles)}条")
    
    print(f"\n📊 列表总计: {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"✅ ({len(content)}字)")
            if len(batch) >= 10:
                save_to_db(batch)
                total_saved += len(batch)
                batch = []
        else:
            print("⚠ 无正文")
    
    if batch:
        save_to_db(batch)
        total_saved += len(batch)
    
    print(f"\n{'='*50}")
    print(f"✅ 完成! 入库: {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()
