#!/usr/bin/env python3
"""黄埔区-建设项目环境影响评价信息 爬虫

NFCMS（广东政府网站群）
列表: /hpqgzkfqzdlyzl/hjbh/jsxmhjyxpjxx/index.html (仅1页14条)
详情: /.../content/post_{id}.html
内容: div#zoomcon > p
日期: 发布时间：YYYY-MM-DD (span.article-create_time)
"""

import requests
import re
import sys
import json
import time
import os
import argparse
from bs4 import BeautifulSoup
from urllib.parse import urljoin

sys.path.insert(0, '/root/gov_crawler')
from crawler_lib import push_to_searchdb
import sqlite3

DB_PATH = '/root/search.db'


def get_db_connection():
    try:
        conn = sqlite3.connect(DB_PATH, timeout=30)
        conn.execute("PRAGMA busy_timeout=30000")
        conn.execute("PRAGMA journal_mode=WAL")
        return conn
    except Exception as e:
        print(f'  WARN DB connect: {e}')
        return None


BASE_URL = 'https://www.hp.gov.cn'
LIST_URL = '/hpqgzkfqzdlyzl/hjbh/jsxmhjyxpjxx/index.html'

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,*/*;q=0.8',
    'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8',
}

SITE_NAME = '黄埔区-建设项目环评'

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


def parse_list(html):
    """解析列表页"""
    soup = BeautifulSoup(html, 'html.parser')
    items = []

    ul = soup.find('ul', class_='infoList')
    if not ul:
        return items

    for li in ul.find_all('li', recursive=False):
        a = li.find('a', href=True)
        if not a:
            continue

        href = a.get('href', '')
        if '/content/post_' not in href:
            continue

        title = a.get('title', '') or a.get_text(strip=True)
        if not title:
            continue

        detail_url = href if href.startswith('http') else urljoin(BASE_URL, href)

        # 日期
        span = li.find('span')
        pub_date = span.get_text(strip=True) if span else ''

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

    return items


def fetch_detail(item):
    """抓取详情页"""
    url = item['url']

    try:
        resp = sess.get(url, timeout=15)
        resp.encoding = 'utf-8'
        html = resp.text
    except Exception as e:
        print(f'  WARN skip: {url} - {e}')
        return item['title'], item.get('pub_date', ''), '', []

    soup = BeautifulSoup(html, 'html.parser')

    # 标题
    h1 = soup.find('h1')
    title = h1.get_text(strip=True) if h1 else item['title']

    # 日期
    date_span = soup.find('span', class_='article-create_time')
    pub_date = ''
    if date_span:
        txt = date_span.get_text(strip=True)
        m = re.search(r'(\d{4}-\d{2}-\d{2})', txt)
        if m:
            pub_date = m.group(1)

    if not pub_date:
        pub_date = item.get('pub_date', '')

    # 正文
    content_div = soup.find('div', id='zoomcon')
    content = ''
    if content_div:
        parts = []
        for elem in content_div.find_all(['p', 'table', 'img'], recursive=True):
            if elem.name == 'p':
                if elem.find('p'):
                    continue
                txt = ''
                for child in elem.children:
                    if isinstance(child, str):
                        t = child.strip()
                        if t:
                            txt += t + ' '
                    elif child.name == 'br':
                        txt += '\n'
                    elif child.name == 'img':
                        src = child.get('src', '')
                        alt = child.get('alt', '')
                        if src:
                            full_src = urljoin(url, src)
                            txt += f'![{alt}]({full_src}) '
                    elif child.name == 'a':
                        a_href = child.get('href', '')
                        a_text = child.get_text(strip=True)
                        if a_href and a_text:
                            full_href = urljoin(url, a_href)
                            txt += f'[{a_text}]({full_href}) '
                    elif child.name in ('span', 'strong', 'b', 'em'):
                        txt += child.get_text(' ', strip=True) + ' '
                txt = re.sub(r'[ \t]+', ' ', txt).strip()
                if txt:
                    parts.append(txt)
            elif elem.name == 'table':
                parts.append(str(elem))
            elif elem.name == 'img':
                src = elem.get('src', '')
                alt = elem.get('alt', '')
                if src:
                    full_src = urljoin(url, src)
                    parts.append(f'![{alt}]({full_src})')
        content = '\n\n'.join(parts)

    # 附件
    attachments = []
    rel_div = soup.find('div', class_='rel_news')
    if rel_div:
        for a in rel_div.find_all('a', href=True):
            href = a.get('href', '')
            text = a.get_text(strip=True)
            if href and text and '/content/post_' not in href:
                if not href.startswith('http'):
                    href = urljoin(url, href)
                attachments.append({'name': text, 'url': href})
                content += f'\n\n<p><a href="{href}">{text}</a></p>'

    return title, pub_date, content, attachments


def main():
    parser = argparse.ArgumentParser(description='黄埔区-建设项目环评')
    parser.add_argument('--pages', type=int, default=1, help='页数（仅1页）')
    args = parser.parse_args()

    # 列表
    print('Fetching list...')
    resp = sess.get(BASE_URL + LIST_URL, timeout=30)
    resp.encoding = 'utf-8'
    items = parse_list(resp.text)
    print(f'Found {len(items)} items')

    # 详情
    records = []
    for i, item in enumerate(items):
        print(f'  [{i+1}/{len(items)}] {item["title"][:40]}...')
        title, pub_date, content, attachments = fetch_detail(item)

        if not title:
            title = item['title']

        title = re.sub(r'\s+', ' ', title).strip()

        try:
            summary = content[:500] if content else ''
        except:
            summary = ''

        record = {
            'url': item['url'],
            'source_url': item['url'],
            'title': title,
            'content': content,
            'summary': summary,
            'pub_date': pub_date,
            'site_name': SITE_NAME,
            'attachments': json.dumps(attachments, ensure_ascii=False) if attachments else '',
        }
        records.append(record)
        time.sleep(0.3)

    # 入库
    print(f'\nInserting {len(records)} records...')
    push_to_searchdb(records, SITE_NAME)

    # FTS验证
    conn = get_db_connection()
    if conn:
        try:
            cursor = conn.execute(
                "SELECT COUNT(*) FROM gov_raw WHERE site_name=?", (SITE_NAME,)
            )
            raw_count = cursor.fetchone()[0]
            cursor = conn.execute(
                "SELECT COUNT(*) FROM gov_search WHERE site_name=?", (SITE_NAME,)
            )
            fts_count = cursor.fetchone()[0]
            print(f'DB: {raw_count} rows (FTS: {fts_count} rows)')
        except Exception as e:
            print(f'  WARN DB query: {e}')
        finally:
            conn.close()

    print('DONE')


if __name__ == '__main__':
    main()
