#!/usr/bin/env python3
"""
Crawl 北京中环长青环境科技有限公司 - 公告公示栏
https://www.zhcqhj.com/html/news/gsl/
Pagination: index_2.html ... index_4.html (4 pages, ~95 items)
List: <td class="news_list"> with table containing links + dates
Detail: <td id="text"> HTML content
Date: <td class="info_text">时间：YYYY-MM-DD HH:MM:SS</td>
"""

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

BASE_URL = 'https://www.zhcqhj.com/html/news/gsl/'
OUTPUT_FILE = '/root/gov_crawler/output/zhcqhj_gsl.jsonl'

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',
}

os.makedirs(os.path.dirname(OUTPUT_FILE), exist_ok=True)

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

# ─── 正文取文本（2026-09-11）：行内节点直接拼接，只在块级边界 / <br> 处换行 ───
# ⚠️ 不要用 el.get_text("\n") 取正文 —— 它是「每个**文本节点**之间插 \n」，Word 粘贴的
#    公文把一行拆成 <span>提取码：</span>pwaj<span>。查阅…</span>，这些行内节点于是各自
#    成行（福泉 id=2095080103703914437 实例：`提取码：`/`pwaj`/`。查阅…` 各占一行）。
_BLOCK_TAGS = {'address', 'article', 'aside', 'blockquote', 'details', 'dialog', 'dd', 'div',
               'dl', 'dt', 'fieldset', 'figcaption', 'figure', 'footer', 'form', 'h1', 'h2',
               'h3', 'h4', 'h5', 'h6', 'header', 'hgroup', 'hr', 'li', 'main', 'nav', 'ol',
               'p', 'pre', 'section', 'table', 'tbody', 'thead', 'tfoot', 'tr', 'td', 'th',
               'ul', 'center', 'caption'}


def body_text(el):
    """块级边界出换行、行内节点直接拼接、<br> 出换行（≈ 浏览器看到的换行结构）。"""
    if el is None:
        return ''
    import re as _re
    from bs4 import NavigableString
    out = []

    def walk(node):
        for ch in node.children:
            if isinstance(ch, NavigableString):
                out.append(str(ch))
            elif getattr(ch, 'name', None) == 'br':
                out.append('\n')
            elif getattr(ch, 'name', None) in _BLOCK_TAGS:
                out.append('\n')
                walk(ch)
                out.append('\n')
            else:
                walk(ch)
    walk(el)
    t = ''.join(out)
    t = _re.sub(r'[ \t\r\f\v]*\n[ \t\r\f\v]*', '\n', t)
    t = _re.sub(r'\n{3,}', '\n\n', t)
    return t.strip()


def get_page_url(page_num):
    if page_num == 1:
        return BASE_URL
    return f'https://www.zhcqhj.com/html/news/gsl/index_{page_num}.html'

def parse_list(html, base_url):
    """Extract article links and dates from a list page."""
    soup = BeautifulSoup(html, 'html.parser')
    items = []
    
    seen = set()
    # Find all links to article HTML files (not index pages)
    for a in soup.find_all('a', href=True):
        href = a['href']
        # Article links end in numbers like /1512.html or /2020-04-12/19.html
        if href.endswith('.html') and 'gsl' in href and 'index_' not in href:
            if href in seen:
                continue
            seen.add(href)
            
            title = a.get('title', '') or a.get_text(strip=True)
            full_url = urljoin(base_url, href)
            
            # Find associated date - look in the same row
            date = ''
            parent_tr = a.find_parent('tr')
            if parent_tr:
                td_cells = parent_tr.find_all('td')
                for td in td_cells:
                    td_text = td.get_text(strip=True)
                    m = re.search(r'(\d{4}-\d{1,2}-\d{1,2})', td_text)
                    if m:
                        date = m.group(1)
                        break
            
            items.append({'url': full_url, 'title': title, 'date': date})
    
    return items

def parse_detail(url, html):
    """Extract title, date, content from a detail page."""
    soup = BeautifulSoup(html, 'html.parser')
    
    # Title from <title> tag - format: "标题 - 中环长青"
    title_tag = soup.find('title')
    title = ''
    if title_tag:
        full_title = title_tag.get_text(strip=True)
        # Remove trailing " - 中环长青"
        title = re.sub(r'\s*[-–—]\s*中环长青\s*$', '', full_title).strip()
    
    # Date from info_text td
    pub_date = ''
    info_td = soup.find('td', class_='info_text')
    if info_td:
        m = re.search(r'(\d{4}-\d{1,2}-\d{1,2})', info_td.get_text())
        if m:
            pub_date = m.group(1)
    
    # Content from td#text
    content_td = soup.find('td', id='text')
    content_html = ''
    text_summary = ''
    if content_td:
        # Clean inline styles but keep structure
        for tag in content_td.find_all(True):
            attrs_to_keep = ['href', 'src', 'alt', 'target', 'style']  # keep style for now
            for attr in list(tag.attrs):
                if attr not in attrs_to_keep:
                    del tag[attr]
        content_html = str(content_td)
        text_summary = body_text(content_td)
    
    # Attachments
    attachments = []
    if content_td:
        for a in content_td.find_all('a', href=True):
            ahref = a.get('href', '')
            if any(ahref.lower().endswith(ext) for ext in ['.pdf', '.doc', '.docx', '.xls', '.xlsx', '.zip', '.rar']):
                attachments.append({
                    'url': urljoin(url, ahref) if not ahref.startswith('http') else ahref,
                    'text': a.get_text(strip=True) or os.path.basename(ahref)
                })
    
    return {
        'title': title,
        'pub_date': pub_date,
        'content_html': content_html,
        'summary': text_summary[:500] if text_summary else '',
        'attachments': attachments
    }

def crawl_all():
    total_pages = 4  # Known from analysis
    
    all_items = []
    for page in range(1, total_pages + 1):
        url = get_page_url(page)
        print(f'  Page {page}/{total_pages} ({url})')
        try:
            resp = session.get(url, timeout=30)
            resp.encoding = 'utf-8'
            items = parse_list(resp.text, url)
            print(f'    Found {len(items)} items')
            all_items.extend(items)
        except Exception as e:
            print(f'    [ERROR] {e}')
        time.sleep(0.5)
    
    # Deduplicate by URL
    seen_urls = set()
    unique_items = []
    for item in all_items:
        if item['url'] not in seen_urls:
            seen_urls.add(item['url'])
            unique_items.append(item)
    print(f'\nTotal unique items: {len(unique_items)}')
    
    # Crawl details
    record_count = 0
    with open(OUTPUT_FILE, 'w', encoding='utf-8') as f:
        for i, item in enumerate(unique_items):
            print(f'  [{i+1}/{len(unique_items)}] {item["title"][:40]}...')
            try:
                resp = session.get(item['url'], timeout=30)
                resp.encoding = 'utf-8'
                detail = parse_detail(item['url'], resp.text)
                
                # Use a[title] from list page as primary title (it's the complete one)
                title = item['title']
                # But if detail has a better title (not empty), use it
                if detail['title'] and len(detail['title']) >= len(item['title']):
                    title = detail['title']
                
                record = {
                    'title': title,
                    'url': item['url'],
                    'date': detail['pub_date'] or item['date'],
                    'content': detail['content_html'],
                    'summary': detail['summary'],
                    'site_name': '北京中环长青环境科技有限公司',
                    'group': '企业',
                    'attachments': json.dumps(detail['attachments'], ensure_ascii=False) if detail['attachments'] else '',
                }
                f.write(json.dumps(record, ensure_ascii=False) + '\n')
                record_count += 1
            except Exception as e:
                print(f'    [ERROR] {item["url"]}: {e}')
            time.sleep(0.3)
    
    print(f'\nDone! {record_count} records written to {OUTPUT_FILE}')

if __name__ == '__main__':
    is_incremental = '--incremental' in sys.argv
    if is_incremental:
        # Only crawl page 1
        print('Incremental mode: crawling page 1 only')
        resp = session.get(BASE_URL, timeout=30)
        resp.encoding = 'utf-8'
        items = parse_list(resp.text, BASE_URL)
        print(f'  Found {len(items)} items on page 1')
        
        with open(OUTPUT_FILE, 'w', encoding='utf-8') as f:
            for item in items:
                try:
                    resp = session.get(item['url'], timeout=30)
                    resp.encoding = 'utf-8'
                    detail = parse_detail(item['url'], resp.text)
                    title = detail['title'] if detail['title'] else item['title']
                    record = {
                        'title': title,
                        'url': item['url'],
                        'date': detail['pub_date'] or item['date'],
                        'content': detail['content_html'],
                        'summary': detail['summary'],
                        'site_name': '北京中环长青环境科技有限公司',
                        'group': '企业',
                        'attachments': json.dumps(detail['attachments'], ensure_ascii=False) if detail['attachments'] else '',
                    }
                    f.write(json.dumps(record, ensure_ascii=False) + '\n')
                except Exception as e:
                    print(f'    [ERROR] {item["url"]}: {e}')
                time.sleep(0.3)
        print(f'Incremental done: {len(items)} records')
    else:
        crawl_all()
