#!/usr/bin/env python3
"""包头市生态环境局 - 公示公告爬虫
站点: sthjj.baotou.gov.cn
栏目: gsgg (公示公告)
CMS: TRS (Terton) - 仅首页第一页静态HTML可用
"""

import requests
import sqlite3
import re
import sys
import os
from datetime import datetime, timedelta
from bs4 import BeautifulSoup

BASE_URL = "http://sthjj.baotou.gov.cn"
LIST_URL = BASE_URL + "/gsgg/index.html"
DB_PATH = "/root/search.db"
SITE_NAME = "sthjj.baotou.gov.cn"

HEADERS = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.0.0 Safari/537.36",
    "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8",
    "Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8",
}

def init_db():
    conn = sqlite3.connect(DB_PATH, timeout=60)
    conn.execute("PRAGMA journal_mode=WAL")
    return conn

def fetch_page(url, timeout=30):
    try:
        resp = requests.get(url, headers=HEADERS, timeout=timeout, verify=False)
        resp.encoding = 'utf-8'
        if resp.status_code == 200:
            return resp.text
        return None
    except:
        return None

def parse_list(html):
    items = []
    soup = BeautifulSoup(html, 'html.parser')
    ul = soup.find('ul', class_='list')
    if not ul:
        return items
    for li in ul.find_all('li', recursive=False):
        a = li.find('a')
        if not a or not a.get('href'):
            continue
        href = a['href'].strip()
        if href.startswith('./'):
            href = BASE_URL + '/gsgg/' + href[2:]
        elif not href.startswith('http'):
            href = BASE_URL + '/gsgg/' + href
        spans = a.find_all('span')
        title = spans[0].get_text(strip=True) if spans else a.get_text(strip=True)
        pub_date = ''
        if len(spans) >= 2:
            d = spans[1].get_text(strip=True)
            d = d.strip('[]')
            pub_date = d
        items.append({'url': href, 'title': title, 'pub_date': pub_date})
    return items

def parse_detail(html, url):
    soup = BeautifulSoup(html, 'html.parser')
    
    # 标题
    title_el = soup.find('meta', attrs={'name': 'ArticleTitle'})
    title = title_el['content'] if title_el else ''
    
    # 正文 - TRS_UEDITOR
    content_div = soup.find('div', class_='TRS_UEDITOR')
    if not content_div:
        content_div = soup.find('div', class_='trs_editor_view')
    
    content = ''
    if content_div:
        # 移除脚本
        for tag in content_div.find_all(['script', 'style']):
            tag.decompose()
        # 正则剥离span标签防止日期被拆
        raw_html = str(content_div)
        raw_html = re.sub(r'</?span[^>]*>', '', raw_html, flags=re.IGNORECASE)
        raw_html = re.sub(r'</?(?:b|font|strong|em|u|i|a)[^>]*>', '', raw_html, flags=re.IGNORECASE)
        content_div_clean = BeautifulSoup(raw_html, 'html.parser')
        # 提取表格HTML - 只取数据表，去重
        tables_html = ''
        seen_texts = set()
        for table in content_div.find_all('table'):
            rows = table.find_all('tr')
            # 跳过布局表：没有3列以上的数据行
            has_data_row = any(len(row.find_all('td')) >= 3 for row in rows)
            if not has_data_row:
                continue
            # 检查表头是否像数据表：每个单元格文本应较短（表头特征）
            first_row = rows[0] if rows else None
            if first_row:
                cells = first_row.find_all(['td', 'th'])
                # 数据表的表头：所有单元格文本都较短 (<= 40)
                is_data_header = all(len(c.get_text(strip=True)) <= 40 for c in cells) if cells else False
                if not is_data_header:
                    continue
            # 去重
            content_text = table.get_text(strip=True)
            if content_text in seen_texts:
                continue
            seen_texts.add(content_text)
            tables_html += str(table) + '\n\n'
        # 移除表格标签，防止表格内容在纯文本中双份出现
        for tag in content_div_clean.find_all('table'):
            tag.decompose()
        content = content_div_clean.get_text(separator='\n\n', strip=True)
        content = re.sub(r'\n{4,}', '\n\n', content)
        if tables_html:
            content += '\n\n[表格]\n' + tables_html
    
    # 发布时间
    pub_date = ''
    pub_meta = soup.find('meta', attrs={'name': 'PubDate'})
    if pub_meta and pub_meta.get('content'):
        m = re.search(r'(\d{4}-\d{2}-\d{2})', pub_meta['content'])
        if m:
            pub_date = m.group(1)
    
    # 附件
    attachments = []
    base_dir = os.path.dirname(url)
    for a_tag in soup.find_all('a', href=True):
        href = a_tag['href']
        if re.search(r'\.(pdf|doc|docx|xls|xlsx|rar|zip)$', href, re.I):
            if href.startswith('./'):
                full_url = base_dir + '/' + href[2:]
            elif href.startswith('/'):
                full_url = BASE_URL + href
            elif not href.startswith('http'):
                full_url = base_dir + '/' + href
            else:
                full_url = href
            fname = a_tag.get_text(strip=True) or os.path.basename(href)
            attachments.append({'name': fname, 'url': full_url})
    
    return {
        'title': title,
        'content': content,
        'pub_date': pub_date,
        'attachments': attachments,
    }

def deduplicate(conn, items):
    cur = conn.execute("SELECT page_url FROM gov_raw WHERE site_name = ?", (SITE_NAME,))
    existing = set(row[0] for row in cur.fetchall())
    return [it for it in items if it['url'] not in existing]

def main(mode='full'):
    conn = init_db()
    
    print(f"[{SITE_NAME}] Fetching list page...")
    html = fetch_page(LIST_URL)
    if not html:
        print("ERROR: Could not fetch list page")
        conn.close()
        return
    
    items = parse_list(html)
    print(f"  Found {len(items)} items on first page")
    
    if not items:
        conn.close()
        return
    
    today = datetime.now().strftime('%Y-%m-%d')
    yesterday = (datetime.now() - timedelta(days=1)).strftime('%Y-%m-%d')
    
    if mode == 'incremental':
        items = [it for it in items if it.get('pub_date') in (today, yesterday)]
        print(f"  After date filter: {len(items)} items")
        if not items:
            print(f"  No new items")
            conn.close()
            return
    
    new_items = deduplicate(conn, items)
    print(f"  New items to crawl: {len(new_items)}")
    
    if not new_items:
        conn.close()
        return
    
    added = 0
    for item in new_items:
        print(f"  Fetching: {item['title'][:50]}...")
        detail_html = fetch_page(item['url'])
        if not detail_html:
            continue
        
        detail = parse_detail(detail_html, item['url'])
        
        # 构建正文
        content = detail['content']
        if detail['attachments']:
            content += '\n\n---\n附件:\n'
            for att in detail['attachments']:
                content += f"\n[{att['name']}]({att['url']})"
        
        try:
            conn.execute("""
                INSERT OR IGNORE INTO gov_raw (site_name, source_url, page_url, title, publish_date, summary, content)
                VALUES (?, ?, ?, ?, ?, ?, ?)
            """, (
                SITE_NAME, item['url'], item['url'],
                detail['title'] or item['title'],
                detail['pub_date'] or item.get('pub_date', ''),
                item['title'][:200], content
            ))
            conn.commit()
            added += 1
            if added % 5 == 0:
                print(f"    Progress: {added}/{len(new_items)}")
        except Exception as e:
            print(f"    DB error: {e}")
    
    print(f"\n  Done! Added {added} new articles")
    
    # 更新FTS
    conn.execute("""
        DELETE FROM gov_search WHERE rowid IN (
            SELECT id FROM gov_raw WHERE site_name = ?
        )
    """, (SITE_NAME,))
    conn.execute("""
        INSERT INTO gov_search(rowid, site_name, title, summary)
        SELECT id, site_name, title, summary FROM gov_raw WHERE site_name = ?
    """, (SITE_NAME,))
    conn.commit()
    conn.close()

if __name__ == "__main__":
    mode = sys.argv[1] if len(sys.argv) > 1 else 'full'
    main(mode)
