#!/usr/bin/env python3
"""北京中环长青环境科技有限公司 - 公告公示栏爬虫
站点: www.zhcqhj.com
栏目: /html/news/gsl/ (公告公示栏)
"""

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

BASE_URL = "http://www.zhcqhj.com"
LIST_PATH = "/html/news/gsl/"
DB_PATH = "/root/search.db"
SITE_NAME = "www.zhcqhj.com-gsl"

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, page_num):
    """解析列表页，返回 (url, title, date) 列表"""
    items = []
    soup = BeautifulSoup(html, 'html.parser')
    # 所有文章链接：<a href="http://www.zhcqhj.com/html/news/gsl/1512.html" title="完整标题">显示标题</a>
    for a_tag in soup.find_all('a', href=True):
        href = a_tag['href'].strip()
        # 只匹配文章链接
        m = re.match(r'http://www\.zhcqhj\.com/html/news/gsl/(\d+)\.html$', href)
        if not m:
            continue
        # 优先用title属性(完整标题)，回退到显示文本
        title = (a_tag.get('title') or a_tag.get_text(strip=True) or '').strip()
        # 找同级的 <span> 日期
        date_span = a_tag.find_next_sibling('span')
        if not date_span:
            date_span = a_tag.parent.find('span') if a_tag.parent else None
        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 ''
        if title:
            items.append({'url': href, 'title': title, 'pub_date': pub_date})
    return items

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

    # 标题
    title_el = soup.find('h1')
    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()

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

    # 正文 - td#text
    content_td = soup.find('td', id='text')
    attachments = []
    content = ''

    if content_td:
        # 提取附件链接（.doc/.pdf/.xls等）
        for a_tag in content_td.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)
                attachments.append({'url': href, 'title': att_title})
            # 百度网盘链接也作为附件
            elif 'pan.baidu.com' in href:
                att_title = a_tag.get_text(strip=True) or '百度网盘'
                if not href.startswith('http'):
                    href = 'http:' + href if href.startswith('//') else requests.compat.urljoin(url, href)
                attachments.append({'url': href, 'title': att_title})

        # 移除脚本/style
        for tag in content_td.find_all(['script', 'style']):
            tag.decompose()

        # 提取表格HTML
        tables_html = ''
        seen_texts = set()
        for table in content_td.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_td_clean = BeautifulSoup(str(content_td), 'html.parser')
        for tag in content_td_clean.find_all('table'):
            tag.decompose()

        content = content_td_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, script_name) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, 'published', '公告公示', 0, 'crawl_zhcqhj_gsl.py')
    """, (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

    for page in range(max_pages):
        if page == 0:
            list_url = BASE_URL + LIST_PATH
        else:
            list_url = BASE_URL + LIST_PATH + f"index_{page+1}.html"

        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, page)
        print(f"  Found {len(items)} articles")

        if not items:
            print(f"  No items found, stopping")
            break

        for item in 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:
                    print(f"  [SKIP] already exists: {title[:40]}...")
                    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)
