#!/usr/bin/env python3
"""章贡区人民政府 - 行政许可爬虫
站点: www.zgq.gov.cn (章贡区, 赣州, 江西)
栏目: /zgqxxgk/c114459/jlist.shtml (行政许可, 区行政审批局)
CMS: 章贡区信息公开系统
"""

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

BASE_URL = "https://www.zgq.gov.cn"
LIST_URL = BASE_URL + "/zgqxxgk/c114459/jlist.shtml"
DB_PATH = "/root/search.db"
SITE_NAME = "www.zgq.gov.cn-xzxk"

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)
        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):
    """解析列表页"""
    items = []
    soup = BeautifulSoup(html, 'html.parser')

    # 查找文章链接: /zgqxxgk/c114459/YYYYMM/*.shtml
    for a in soup.find_all('a'):
        href = a.get('href', '').strip()
        text = a.get_text(strip=True)

        # 过滤：必须是以.shtml结尾的内容链接（带日期路径）
        if not href.endswith('.shtml'):
            continue
        if not href.startswith('/zgqxxgk/c114459/'):
            continue
        if len(text) < 8:
            continue

        # 构建完整URL
        if href.startswith('/'):
            full_url = BASE_URL + href
        elif href.startswith('http'):
            full_url = href
        else:
            full_url = BASE_URL + '/' + href

        # 取列表标题
        title = a.get('title') or text
        title = re.sub(r'\s+', ' ', title).strip()

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

    return items


def parse_detail(html, url):
    """解析详情页"""
    soup = BeautifulSoup(html, 'html.parser')

    # ── 标题 ──
    title = ''
    ucap = soup.find('ucaptitle')
    if ucap:
        title = ucap.get_text(strip=True)
    if not title:
        h1 = soup.find('h1', class_='article-title')
        if h1:
            title = h1.get_text(strip=True)

    # ── 发布时间 ──
    pub_date = ''
    pt = soup.find('PUBLISHTIME')
    if pt:
        m = re.search(r'(\d{4}-\d{2}-\d{2})', pt.get_text())
        if m:
            pub_date = m.group(1)
    if not pub_date:
        # meta meta-data 生成日期
        meta_div = soup.find('div', class_='meta-data')
        if meta_div:
            m = re.search(r'生成日期[：:]\s*(\d{4}-\d{2}-\d{2})', meta_div.get_text())
            if m:
                pub_date = m.group(1)

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

    # UCAPCONTENT 兜底（自定义标签）
    content = ''
    ucap_c = soup.find('ucapcontent')
    if ucap_c:
        content = ucap_c.get_text(separator='\n\n', strip=True)

    # 附件
    attachments = []
    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})

    # 表格 + 段落
    tables_html = ''
    if content_div:
        # 清理script/style
        for tag in content_div.find_all(['script', 'style']):
            tag.decompose()

        # 提取表格
        seen_tables = set()
        for table in content_div.find_all('table'):
            txt = table.get_text(strip=True)
            if txt in seen_tables:
                continue
            seen_tables.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)
        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 = LIST_URL
        else:
            list_url = LIST_URL.replace('.shtml', f'_{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)
        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']

            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
                continue

            detail_title, content, pub_date, attachments = parse_detail(detail_html, url)

            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)
