#!/usr/bin/env python3
"""镇江经济技术开发区 - 通告公示爬虫
站点: www.zjna.gov.cn
栏目: /zjna/tztg/xxgk_list.shtml (通知通告+便民/办事公示)
"""

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

BASE_URL = "http://www.zjna.gov.cn"
LIST_PATH = "/zjna/tztg/"
DB_PATH = "/root/search.db"
SITE_NAME = "www.zjna.gov.cn-tztg"

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 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')
    # 文章列表在 ul.pageList.newsList 内
    for ul in soup.find_all('ul', class_='pageList'):
        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 not href.endswith('.shtml'):
                continue
            # 完整URL
            if href.startswith('/'):
                href = BASE_URL + href
            elif href.startswith('http'):
                pass
            else:
                href = BASE_URL + '/' + href
            # 标题 - 优先取 title 属性(完整)，回退到显示文本
            title = (a.get('title') or a.get_text(strip=True) or '').strip()
            title = re.sub(r'\s+', ' ', title)
            if not title:
                continue
            # 日期
            date_span = li.find('span', class_='time')
            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')

    # 标题 - div.biaoti
    title_el = soup.find('div', class_='biaoti')
    title = title_el.get_text(strip=True) if title_el 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()

    # 发布时间 - div.article-attr
    pub_date = ''
    attr_div = soup.find('div', class_='article-attr')
    if attr_div:
        date_match = re.search(r'(\d{4}-\d{2}-\d{2})', attr_div.get_text())
        if date_match:
            pub_date = date_match.group(1)

    # 正文 - div.article-content.article-content-body
    content_div = soup.find('div', class_='article-content')
    if not content_div:
        content_div = soup.find('div', class_='article-content-body')

    # 附件 - div.article-appendixs
    attachments = []
    appendix_div = soup.find('div', class_='article-appendixs')
    if appendix_div:
        for a_tag in appendix_div.find_all('a'):
            href = a_tag.get('href', '')
            if not href.startswith('http'):
                href = requests.compat.urljoin(url, href)
            att_title = a_tag.get_text(strip=True) or os.path.basename(href)
            attachments.append({'url': href, 'title': att_title})

    content = ''
    tables_html = ''
    if content_div:
        # 附件也在内容里找
        for a_tag in content_div.find_all('a'):
            href = a_tag.get('href', '')
            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:
                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()

        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

    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):
    import json
    attachments_json = json.dumps(attachments, ensure_ascii=False) if attachments else '[]'
    now = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
    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)
        VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, 'published', '通告公示', 0)
    """, (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 + "xxgk_list.shtml"
        else:
            list_url = BASE_URL + LIST_PATH + f"xxgk_list_{page+1}.shtml"

        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)
        # 去重（站内分页有跨页重复的可能）
        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
                print(f"    ✓ saved [{pub_date}] {detail_title[:50]}...")
            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)
