#!/usr/bin/env python3
"""
咸安区-生态环境局-重大建设项目 爬虫
https://www.xianan.gov.cn/xxgk/dfbmptlj/bmxxgkpt/qsthjj/fdzdgknr_19646/zdjsxm/
TRS CMS, 单页(8条), ul.info-list > li
"""
import sys
import time
import requests
import sqlite3
from bs4 import BeautifulSoup
from urllib.parse import urljoin

DB_PATH = "/mnt/data/search.db"
BASE_URL = "http://www.xianan.gov.cn/xxgk/dfbmptlj/bmxxgkpt/qsthjj/fdzdgknr_19646/zdjsxm/"
SITE_NAME = "咸安区-生态环境局-重大建设项目"

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",
}

def crawl_list():
    """Parse the single list page"""
    r = requests.get(BASE_URL, headers=HEADERS, timeout=30)
    r.encoding = 'utf-8'
    soup = BeautifulSoup(r.text, 'html.parser')
    
    ul = soup.find('ul', class_='info-list')
    if not ul:
        print("ERROR: ul.info-list not found")
        return []
    
    results = []
    for li in ul.find_all('li', recursive=False):
        a = li.find('a', href=True)
        sp = li.find('span')
        if not a:
            continue
        
        href = a['href'].strip()
        title = a.get('title', '') or a.get_text(strip=True)
        date = sp.get_text(strip=True) if sp else ''
        
        if not title or len(title) < 3:
            continue
        
        full_url = urljoin(BASE_URL, href)
        results.append({'title': title, 'url': full_url, 'date': date})
    
    return results


def fetch_detail(item):
    """Parse detail page"""
    r = requests.get(item['url'], headers=HEADERS, timeout=30)
    r.encoding = 'utf-8'
    soup = BeautifulSoup(r.text, 'html.parser')
    
    # Content
    content_div = soup.select_one('div.view.TRS_UEDITOR')
    if not content_div:
        content_div = soup.select_one('div.doc-content')
    if not content_div:
        content_div = soup.find('div', class_=lambda x: x and 'TRS_Editor' in (x or ''))
    if not content_div:
        print(f"  No content found for {item['url']}")
        return None
    
    # Remove scripts, styles, iframes
    for tag in content_div.find_all(['script', 'style', 'iframe']):
        tag.decompose()
    
    # Extract text with paragraph separation
    parts = []
    for child in content_div.children:
        tag = getattr(child, 'name', None)
        if tag == 'p':
            txt = child.get_text(separator='', strip=True)
            if txt:
                parts.append(txt)
        elif tag in ('table',):
            parts.append(str(child))
        elif tag is None and isinstance(child, str):
            txt = child.strip()
            if txt:
                parts.append(txt)
    
    content = '\n\n'.join(parts) if parts else content_div.get_text(separator='', strip=True)
    
    if not content or len(content) < 30:
        print(f"  Content too short for {item['url']}")
        return None
    
    # Title
    title_tag = soup.find('title')
    full_title = title_tag.get_text(strip=True) if title_tag else ''
    full_title = re.sub(r'\s*[-_―]\s*咸安区人民政府.*', '', full_title).strip()
    if not full_title or len(full_title) < len(item['title']):
        full_title = item['title']
    
    return {
        'title': full_title,
        'content': content,
        'date': item['date'],
        'url': item['url'],
        'site_name': SITE_NAME,
    }


def save_to_db(records):
    if not records:
        return 0
    conn = sqlite3.connect(DB_PATH, timeout=60)
    c = conn.cursor()
    inserted = 0
    for rec in records:
        try:
            c.execute(
                "INSERT OR IGNORE INTO gov_raw (title, content, page_url, publish_date, site_name) "
                "VALUES (?, ?, ?, ?, ?)",
                (rec['title'], rec['content'], rec['url'], rec['date'], rec['site_name'])
            )
            if c.rowcount > 0:
                inserted += 1
        except Exception as e:
            print(f"  DB error: {e}")
    conn.commit()
    conn.commit()
    conn.close()
    return inserted


import re

def main():
    print(f"=== {SITE_NAME} ===")
    
    items = crawl_list()
    print(f"List: {len(items)} items")
    
    if not items:
        return
    
    batch = []
    for item in items:
        detail = fetch_detail(item)
        if detail:
            batch.append(detail)
            print(f"  + {detail['date']} | {detail['title'][:40]}")
        time.sleep(0.5)
    
    inserted = save_to_db(batch)
    print(f"\nInserted {inserted}/{len(batch)} new records")


if __name__ == '__main__':
    main()
