#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
平原县人民政府 - 通知公告 爬虫
CMS: 平原县自建 (TRS模板)
列表: index.html (page1) / index_61478998_N.html (page N+1)
详情: h1.cont_t 标题, div.con_time 日期/来源
"""

import re
import sys
import time
import subprocess
from urllib.parse import urljoin

import requests
from bs4 import BeautifulSoup

# ── 配置 ──────────────────────────────────────────
BASE_URL = "https://www.zgpingyuan.gov.cn"
LIST_PATH = "/n30446770/n84207328"
LIST_URL = BASE_URL + LIST_PATH + "/"
SITE_NAME = "平原县人民政府"
GROUP = "山东省"
DB_PATH = "/mnt/data/search.db"
TOTAL_PAGES = 6  # 6页 × ~15条/页

HEADERS = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36",
}

session = requests.Session()
session.headers.update(HEADERS)


def clean_text(text):
    if not text:
        return ""
    text = re.sub(r'(&middot;|&nbsp;|\s)+', ' ', text)
    return text.strip()


def clean_content_html(html_content, detail_url):
    """提取正文，表格保留HTML"""
    if not html_content:
        return ""
    soup = BeautifulSoup(html_content, 'html.parser')
    for tag in soup(['script', 'style']):
        tag.decompose()
    parts = []
    for child in soup.children:
        if not child.name:
            continue
        if child.name == 'p':
            t = child.get_text(strip=True)
            if t:
                parts.append(t)
        elif child.name == 'table':
            parts.append(str(child))
        elif child.name in ('div', 'section', 'article'):
            for p in child.find_all('p', recursive=True):
                if p.find_parent('table'):
                    continue
                t = p.get_text(strip=True)
                if t:
                    parts.append(t)
            for tbl in child.find_all('table', recursive=True):
                parts.append(str(tbl))
        elif child.name == 'img':
            src = child.get('src', '')
            alt = child.get('alt', '')
            if src:
                full_src = urljoin(detail_url, src) if not src.startswith('http') else src
                parts.append(f'![{alt}]({full_src})')
    return '\n\n'.join(parts)


def fetch_list(max_pages=5):
    """获取文章列表"""
    all_items = []
    for page in range(max_pages):
        if page == 0:
            url = LIST_URL + "index.html"
        else:
            url = LIST_URL + f"index_61478998_{page}.html"
        print(f"  第{page+1}页...", end=' ')
        try:
            r = session.get(url, timeout=30)
            r.encoding = 'utf-8'
            if r.status_code != 200:
                print(f"HTTP {r.status_code}")
                break
        except Exception as e:
            print(f"ERR {e}")
            break

        soup = BeautifulSoup(r.text, 'html.parser')
        lis = soup.select('#comp_61478998 ul li')
        if not lis:
            lis = soup.select('li a[href*="content.html"]')
            if not lis:
                print("无列表")
                break

        count = 0
        for li in soup.select('#comp_61478998 ul li') or soup.find_all('li'):
            a = li.find('a') if li.name == 'li' else None
            if not a and li.name == 'li':
                continue
            if not a:
                continue
            href = a.get('href', '')
            if 'content.html' not in href:
                continue
            title_div = a.find('div', class_='text')
            title = clean_text(title_div.get_text()) if title_div else ''
            span = a.find('span')
            date = clean_text(span.get_text()) if span else ''
            if not href or not title:
                continue
            full_url = urljoin(LIST_URL, href)
            all_items.append({'url': full_url, 'title': title, 'date': date})
            count += 1

        print(f"{count}条")
        time.sleep(0.3)
    return all_items


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

    # 1. 标题 - h1.cont_t
    h1 = soup.find('h1', class_='cont_t')
    if h1:
        title = clean_text(h1.get_text())

    # 2. 日期/来源 - div.con_time
    ct = soup.find('div', class_='con_time')
    if ct:
        txt = ct.get_text()
        dm = re.search(r'(\d{4}-\d{2}-\d{2})', txt)
        if dm:
            publish_date = dm.group(1)
        sm = re.search(r'来源[：:]\s*([^\s]+)', txt)
        if sm:
            source = sm.group(1).strip()

    # 3. 正文 - 从con_time后到下一个clear
    ct_div = soup.find('div', class_='con_time')
    if ct_div:
        content_elem = ct_div.find_next_sibling()
        content_parts = []
        while content_elem and 'clear' not in content_elem.get('class', []):
            if content_elem.name == 'p':
                t = content_elem.get_text(strip=True)
                if t:
                    # 附件链接嵌入
                    for a_tag in content_elem.find_all('a', href=True):
                        href = a_tag['href']
                        if re.search(r'\.(pdf|doc|docx|xls|xlsx|zip|rar)$', href, re.I):
                            a_text = a_tag.get_text(strip=True) or href
                            full_url = urljoin(url, href) if not href.startswith('http') else href
                            a_tag.replace_with(soup.new_string(f' [{a_text}]({full_url}) '))
                    content_parts.append(content_elem.get_text(strip=True))
            elif content_elem.name == 'table':
                content_parts.append(str(content_elem))
            content_elem = content_elem.find_next_sibling()
        content = '\n\n'.join(content_parts)

    return title, publish_date, source, content


def insert_article(item, detail_title, pub_date, source, content):
    page_url = item['url'].replace("'", "''")
    title = (detail_title or item['title']).replace("'", "''")
    publish_date = pub_date or item.get('date', '')
    source_name = source or SITE_NAME
    source_name = source_name.replace("'", "''")
    content_safe = content.replace("'", "''")
    summary = title[:200]
    site_name = SITE_NAME

    sql_raw = f"""INSERT OR IGNORE INTO gov_raw 
        (page_url, title, content, publish_date, source_url, site_name, summary, group_name, industry)
    VALUES 
        ('{page_url}', '{title}', '{content_safe}', '{publish_date}', '{page_url}', '{site_name}', '{summary}', '{GROUP}', '政府公告');
"""
    combined_sql = sql_raw + """SELECT CASE WHEN changes() > 0 THEN last_insert_rowid() ELSE 0 END;
"""
    try:
        result = subprocess.run(
            ['sqlite3', "-cmd", ".timeout 60000", DB_PATH],
            input=combined_sql,
            capture_output=True, text=True, timeout=30
        )
        if result.returncode == 0:
            out = result.stdout.strip()
            try:
                rowid = int(out.strip())
            except ValueError:
                rowid = 0
            if rowid > 0:
                fts_sql = f"""INSERT OR IGNORE INTO gov_search (rowid, title, site_name, summary)
SELECT rowid, title, site_name, summary FROM gov_raw WHERE rowid = {rowid};
"""
                subprocess.run(['sqlite3', "-cmd", ".timeout 60000", DB_PATH], input=fts_sql, capture_output=True, text=True, timeout=30)
                return True
        else:
            if 'UNIQUE constraint' not in result.stderr:
                print(f"    [DB] {result.stderr[:200]}")
    except Exception as e:
        print(f"    [DB] 错误: {e}")
    return False


def main(max_pages=5):
    print(f"=== 平原县 - 通知公告 爬虫 ===\n")
    articles = fetch_list(max_pages)
    if not articles:
        print("无文章列表")
        return
    print(f"\n列表总计: {len(articles)} 条")

    known_urls = set()
    try:
        result = subprocess.run(
            ['sqlite3', "-cmd", ".timeout 60000", DB_PATH, "SELECT page_url FROM gov_raw WHERE page_url LIKE '%zgpingyuan.gov.cn%'"],
            capture_output=True, text=True, timeout=30
        )
        if result.returncode == 0 and result.stdout.strip():
            known_urls = set(result.stdout.strip().split('\n'))
    except Exception:
        pass
    print(f"已知URL: {len(known_urls)}")

    added = 0
    skipped = 0
    for i, a in enumerate(articles):
        url = a['url']
        if url in known_urls:
            skipped += 1
            continue

        print(f"  [{i+1}/{len(articles)}] {a['title'][:50]}...", end=' ')
        try:
            r = session.get(url, timeout=30)
            r.encoding = 'utf-8'
        except Exception as e:
            print(f"ERR {e}")
            time.sleep(1)
            continue

        d_title, d_date, d_source, content = parse_detail(r.text, url)
        if not content.strip():
            print("SKIP 无正文")
            skipped += 1
            continue

        if insert_article(a, d_title, d_date, d_source, content):
            added += 1
            print(f"OK ({len(content.strip())}字)")
        else:
            skipped += 1
            print("SKIP (重复或入库失败)")
        time.sleep(0.3)

    print(f"\n结果: 新增 {added} 条, 跳过 {skipped} 条")
    print("=== 完成 ===")


if __name__ == '__main__':
    pages = 5
    if len(sys.argv) > 1:
        for arg in sys.argv[1:]:
            if arg.startswith('--pages='):
                try:
                    pages = int(arg.split('=')[1])
                except ValueError:
                    pass
    main(max_pages=pages)
