#!/usr/bin/env python3
"""章贡区人民政府 - 通知公告爬虫
站点: www.zgq.gov.cn (章贡区, 赣州, 江西)
栏目: /zgqzf/tzgg/list.shtml (通知公告)
CMS: 章贡区主站CMS（同article-content-body）
"""

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

BASE_URL = "https://www.zgq.gov.cn"
LIST_URL = BASE_URL + "/zgqzf/tzgg/list.shtml"
DB_PATH = "/root/search.db"
SITE_NAME = "www.zgq.gov.cn-tzgg"

HEADERS = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/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')
    # 找主内容区ul（ul[5]，12条）
    for ul in soup.find_all('ul'):
        lis = ul.find_all('li', recursive=False)
        count = 0
        for li in lis:
            a = li.find('a')
            if a and '/tzgg/' in a.get('href','') and len(a.get_text(strip=True)) > 5:
                count += 1
        if count >= 10:
            for li in lis:
                a = li.find('a')
                if not a or '/tzgg/' not in a.get('href',''):
                    continue
                href = a['href'].strip()
                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 a.get_text(strip=True) or ''
                title = re.sub(r'\s+', ' ', title).strip()
                if not title or len(title) < 6:
                    continue
                pub_date = ''
                for sp in li.find_all(['span', 'em', 'font']):
                    m = re.search(r'(\d{4}-\d{2}-\d{2})', sp.get_text())
                    if m:
                        pub_date = m.group(1)
                        break
                items.append({'url': full_url, 'title': title, 'pub_date': pub_date})
            break
    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')
        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:
        for tag in soup.find_all(['span', 'p', 'div']):
            m = re.search(r'发布日期[：:]\s*(\d{4}-\d{2}-\d{2})', tag.get_text())
            if m:
                pub_date = m.group(1)
                break
    content_div = soup.find('div', class_='article-content-body')
    if not content_div:
        content_div = soup.find('div', class_='article-content')
    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:
        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 = [p.get_text(strip=True) for p in paragraphs if p.get_text(strip=True)]
            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']
            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
                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='增量模式')
    # Handle bare numeric arg for _MAX_PG
    import sys as _SYS2
    _MAX_PG = int(_SYS2.argv[-1]) if len(_SYS2.argv) > 1 and _SYS2.argv[-1].isdigit() else None
    if _MAX_PG is not None:
        print('[AutoPg] max_pages=' + str(_MAX_PG))
        _SYS2.argv.pop()
    args = parser.parse_args()
    crawl(max_pages=args.max_pages, incremental=args.incremental)
