#!/usr/bin/env python3
"""正镶白旗人民政府 - 通知公告爬虫
站点: www.zxbq.gov.cn (正镶白旗)
栏目: /zxbq/zwgk/zfxxgk/fdzdgknr/tzgg/ (通知公告)
CMS: Huilan (eportal/aisite) 静态页面分页
"""

import requests
import sqlite3
import re
import sys
import os
import json
import urllib3
from datetime import datetime
from bs4 import BeautifulSoup

urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)

# ── Config ──
BASE_URL = "https://www.zxbq.gov.cn"
LIST_PATH = "/zxbq/zwgk/zfxxgk/fdzdgknr/tzgg/"
DB_PATH = "/root/search.db"
SITE_NAME = "www.zxbq.gov.cn-tzgg"

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
        print(f"  [WARN] HTTP {resp.status_code} for {url}", file=sys.stderr)
        return None
    except Exception as e:
        print(f"  [ERROR] fetch failed: {e}", file=sys.stderr)
        return None


def parse_list(html):
    """解析列表页，返回 (url, title, date) 列表"""
    items = []
    soup = BeautifulSoup(html, 'html.parser')

    # 文章列表在 div.con_wrap_list > ul > li
    list_div = soup.find('div', class_='con_wrap_list')
    if not list_div:
        # 也可能在别的位置
        list_div = soup.find('ul', class_=lambda c: c and 'con_wrap' in str(c) if c else False)
    if not list_div:
        # 直接用 ul 查找
        ul = soup.find('ul')
        if ul:
            list_div = ul

    # 找 ul
    ul = list_div.find('ul') if list_div and list_div.name != 'ul' else list_div
    if not ul:
        print("  [WARN] ul not found in con_wrap_list", file=sys.stderr)
        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()
        # 完整URL
        if href.startswith('/'):
            href = BASE_URL + href
        elif href.startswith('http'):
            pass
        else:
            href = BASE_URL + LIST_PATH + href

        # 标题 - 优先取 title 属性(完整)，回退到显示文本
        title = (a.get('title') or a.get_text(strip=True) or '').strip()
        title = re.sub(r'\s+', ' ', title)
        title = re.sub(r'\.\.\.$', '', title).strip()
        if not title:
            continue

        # 日期
        date_span = li.find('span')
        pub_date = date_span.get_text(strip=True) if date_span else ''
        date_match = re.search(r'(\d{4}-\d{2}-\d{2})', pub_date)
        pub_date = date_match.group(1) if date_match else ''

        items.append({'url': href, 'title': title, 'pub_date': pub_date})

    return items


def parse_detail(html, url):
    """解析详情页 - 标题、正文、日期、附件"""
    soup = BeautifulSoup(html, 'html.parser')

    # ── 标题 h1 ──
    h1 = soup.find('h1')
    title = h1.get_text(strip=True) if h1 else ''
    if not title:
        title_tag = soup.find('title')
        if title_tag:
            t = title_tag.get_text(strip=True)
            t = re.sub(r'\s*[-_|]\s*正镶白旗人民政府.*$', '', t)
            title = t.strip()

    # ── 发布时间 ──
    pub_date = ''
    date_p = soup.find('p', class_='easysite-news-describe')
    if date_p:
        date_match = re.search(r'(\d{4}-\d{2}-\d{2})', date_p.get_text())
        if date_match:
            pub_date = date_match.group(1)

    # ── 正文内容 ──
    content_div = soup.find('div', class_='TRS_Editor')
    if not content_div:
        content_div = soup.find('div', class_='BuXiText')

    # ── 附件 ──
    attachments = []
    # 从 JS 变量 attachHuilanMediaArray 中提取附件
    # 格式: attachHuilanMediaArray.push({src:'...',title:'...'});
    script_tags = soup.find_all('script')
    for script in script_tags:
        if script.string and 'attachHuilanMediaArray' in script.string:
            for match in re.finditer(r'attachHuilanMediaArray\.push\(\{src:\'([^\']+)\',title:\'([^\']+)\'',
                                     script.string):
                att_url = match.group(1)
                att_title = match.group(2)
                if not att_url.startswith('http'):
                    att_url = requests.compat.urljoin(url, att_url)
                attachments.append({'url': att_url, 'title': att_title})

    content = ''
    tables_html = ''
    if content_div:
        # 正文中的附件链接
        for a_tag in content_div.find_all('a'):
            href = a_tag.get('href', '').strip()
            if any(href.endswith(ext) for ext in
                   ['.doc', '.docx', '.pdf', '.xls', '.xlsx', '.zip', '.rar', '.ppt', '.pptx']):
                if not href.startswith('http'):
                    href = requests.compat.urljoin(url, href)
                att_title = a_tag.get_text(strip=True) or os.path.basename(href)
                if not any(a['url'] == href for a in attachments):
                    attachments.append({'url': href, 'title': att_title})

        # 移除脚本和样式
        for tag in content_div.find_all(['script', 'style']):
            tag.decompose()

        # 提取表格
        seen_texts = set()
        for table in content_div.find_all('table'):
            rows = table.find_all('tr')
            has_data = any(len(row.find_all('td')) >= 3 for row in rows) if rows else False
            if not has_data and not rows:
                continue
            txt = table.get_text(strip=True)
            if txt in seen_texts:
                continue
            seen_texts.add(txt)
            tables_html += str(table) + '\n\n'

        # 正文文本（不含表格）
        content_div_clean = BeautifulSoup(str(content_div), 'html.parser')
        for tag in content_div_clean.find_all('table'):
            tag.decompose()

        paragraphs = content_div_clean.find_all('p')
        if paragraphs:
            para_texts = []
            for p in paragraphs:
                p_text = p.get_text(strip=True)
                if p_text:
                    para_texts.append(p_text)
            content = '\n\n'.join(para_texts)
        else:
            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\n' + tables_html

    # ── 空内容回退 ──
    if len(content.strip()) < 20:
        content = f'<p><a href="{url}">{title}</a></p>\n'
        for att in attachments:
            content += f'\n附件: [{att["title"]}]({att["url"]})'

    return title, content, pub_date, attachments


def save_article(conn, page_url, title, summary_text, publish_date, attachments, site_name):
    attachments_json = json.dumps(attachments, ensure_ascii=False) if attachments else '[]'
    level = abs(hash(page_url)) % 10 + 1
    conn.execute("""
        INSERT OR REPLACE INTO gov_raw (page_url, site_name, source_url, title, publish_date, summary, content, attachments, date_rank, status, category, visits, script_name) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, 'published', '通知公告', 0, 'crawl_zxbq_tzgg.py')
    """, (page_url, site_name, page_url, title, publish_date, summary_text, summary_text, attachments_json, level))
    conn.commit()


def crawl(max_pages=5, incremental=False):
    conn = init_db()
    total = 0
    errors = 0
    seen_urls = set()

    for page in range(max_pages):
        if page == 0:
            list_url = BASE_URL + LIST_PATH + "index.html"
        else:
            list_url = BASE_URL + LIST_PATH + f"c92754c6-{page+1}.html"

        print(f"[PAGE {page+1}] {list_url}")
        html = fetch_page(list_url)
        if not html:
            print(f"  [WARN] Page {page+1} unreachable, stopping")
            break

        items = parse_list(html)
        if not items:
            print(f"  No articles found, stopping")
            break

        # 去重
        unique_items = [it for it in items if it['url'] not in seen_urls]
        for it in items:
            seen_urls.add(it['url'])
        print(f"  Found {len(items)} articles ({len(unique_items)} new)")

        if not unique_items:
            if page > 0:
                print(f"  No new items, stopping")
                break

        for item in unique_items:
            url = item['url']
            title = item['title']
            list_date = item['pub_date']

            if incremental:
                existing = conn.execute(
                    "SELECT page_url FROM gov_raw WHERE page_url = ?", (url,)
                ).fetchone()
                if existing:
                    continue

            print(f"  [FETCH] {title[:50]}...")
            detail_html = fetch_page(url)
            if not detail_html:
                errors += 1
                print(f"  [ERROR] detail page unreachable: {url}")
                continue

            detail_title, content, pub_date, attachments = parse_detail(detail_html, url)
            if not pub_date and list_date:
                pub_date = list_date

            if detail_title:
                save_article(conn, url, detail_title, content, pub_date, attachments, SITE_NAME)
                total += 1
                att_count = len(attachments)
                att_str = f" +{att_count}附件" if att_count else ""
                print(f"    ✓ saved [{pub_date}] {detail_title[:50]}...{att_str}")
            else:
                print(f"    ✗ empty title, skipped")

    conn.close()
    print(f"\n[DONE] Total: {total} articles, Errors: {errors}")


if __name__ == '__main__':
    import argparse
    parser = argparse.ArgumentParser(description='正镶白旗人民政府通知公告爬虫')
    parser.add_argument('--max-pages', type=int, default=5, help='最大爬取页数')
    parser.add_argument('--incremental', action='store_true', help='增量模式')
    args = parser.parse_args()
    crawl(max_pages=args.max_pages, incremental=args.incremental)
