#!/usr/bin/env python3
"""crawl_bynr_sthj.py - 巴彦淖尔市人民政府-生态环境 (TRS静态 + trs_editor_view)"""
import sys, os, requests, re
from datetime import datetime, timedelta

sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from crawler_lib import push_to_searchdb

CUTOFF = (datetime.now() - timedelta(days=365*3)).strftime('%Y-%m-%d')
SITE_NAME = '巴彦淖尔市-生态环境'
HEADERS = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) Chrome/120.0'}
BASE = 'https://www.bynr.gov.cn/zfxxgk/fdzdgk/zdlyxx/sthj'

def fetch_urls_from_page(page_num):
    if page_num == 0:
        url = BASE + '/'
    else:
        url = f'{BASE}/index_{page_num + 1}.html'
    try:
        r = requests.get(url, timeout=(5, 15), headers=HEADERS, verify=False)
        r.encoding = 'utf-8'
    except:
        return []
    items = re.findall(
        r'<a href="([^"]+)"[^>]*>(.*?)</a>.*?(\d{4}-\d{2}-\d{2})',
        r.text, re.DOTALL
    )
    results = []
    for href, title_html, pub_date in items:
        title = re.sub(r'<[^>]+>', '', title_html).strip()
        title = re.sub(r'\s+', '', title).strip()  # 删除内部换行/空格(中文标题)
        if len(title) < 4:
            continue
        if href.startswith('./'):
            full_url = BASE + href[1:]
        elif href.startswith('/'):
            full_url = 'https://www.bynr.gov.cn' + href
        else:
            full_url = BASE + '/' + href
        results.append({'url': full_url, 'pub_date': pub_date, 'title': title})
    return results

def fetch_detail(url):
    for _attempt in range(2):
        try:
            r = requests.get(url, timeout=(5, 15), headers=HEADERS, verify=False)
            r.encoding = 'utf-8'
            break
        except:
            r = None
    if r is None:
        return '', ''
    # 404 页快速跳过 (重定向到 /404/404.html)
    if '/404/' in r.url:
        return '', ''
    title = ''
    # 优先取页面标题元素, fallback <title> 标签
    # h1 内可含嵌套标签(<UCAPTITLE>等), 提取全部文本再剥标签
    m = re.search(r'<h1[^>]*>(.*?)</h1>', r.text, re.DOTALL)
    if m:
        cand = re.sub(r'<[^>]+>', '', m.group(1)).strip()
        cand = re.sub(r'^begin-->|end-->$', '', cand).strip()
        if cand and '404' not in cand:
            title = cand
    if not title:
        # TRS标准: div.title_bg > h3.title (标题完整, 优先于通用class title)
        m = re.search(r'<div class="title_bg">\s*<h3[^>]*>(.*?)</h3>', r.text, re.DOTALL)
        if m:
            cand = re.sub(r'<[^>]+>', '', m.group(1)).strip()
            cand = re.sub(r'^begin-->|end-->$', '', cand).strip()
            if cand and '404' not in cand:
                title = cand
    if not title:
        for pat in [r'class="[^"]*title[^"]*"[^>]*>\s*([^<]{5,200})\s*<',
                    r'class="[^"]*Title[^"]*"[^>]*>\s*([^<]{5,200})\s*<']:
            m = re.search(pat, r.text, re.DOTALL)
            if m:
                cand = re.sub(r'<[^>]+>', '', m.group(1)).strip()
                cand = re.sub(r'^begin-->|end-->$', '', cand).strip()
                if cand and '404' not in cand:
                    title = cand
                    break
    if not title:
        m = re.search(r'<title>([^<]*)</title>', r.text, re.DOTALL)
        if m:
            title = re.sub(r'<[^>]+>', '', m.group(1)).strip()
            # 显式剥离站点名, 不用字符类split(标题内部连字符如2026-06会被误分割截断)
            title = re.sub(r'\s*[-_|]\s*巴彦淖尔市人民政府\s*$', '', title)
            title = re.sub(r'^\s*巴彦淖尔市人民政府\s*[-_|]\s*', '', title)
            title = re.sub(r'\s*[-_|]\s*巴彦淖尔市政府\s*$', '', title)
            title = re.sub(r'^\s*巴彦淖尔市政府\s*[-_|]\s*', '', title)
    title = re.sub(r'\s+', '', title).strip()  # 删除内部换行/空格
    content = ''
    m = re.search(r'<div class="trs_editor_view TRS_UEDITOR[^"]*"[^>]*>(.*?)</div>\s*</div>', r.text, re.DOTALL)
    if m:
        content = m.group(1).strip()
    if not content:
        m = re.search(r'<div class="inner">(.*?)<div class="details_handle">', r.text, re.DOTALL)
        if m:
            content = m.group(1).strip()
    if not content:
        # 旧模板(2026-05前文章): <div class=TRS_Editor> 无引号class
        m = re.search(r'<div class=TRS_Editor>(.*?)</div>\s*</div>', r.text, re.DOTALL)
        if m:
            content = m.group(1).strip()
    return title, content

def run(incremental=False):
    records = []
    seen = set()
    max_pages = 1 if incremental else 30
    for pg in range(max_pages):
        items = fetch_urls_from_page(pg)
        if not items:
            break
        print(f"  Page {pg+1}: {len(items)} items")
        for it in items:
            if it['pub_date'] < CUTOFF:
                continue
            if it['url'] in seen:
                continue
            seen.add(it['url'])
            title, content = fetch_detail(it['url'])
            if not title or not content.strip():
                continue
            records.append({
                'title': title,
                'url': it['url'],
                'pub_date': it['pub_date'],
                'site_name': SITE_NAME,
                'content': content,
                'summary': '',
            })
    print(f"  Total: {len(records)} items")
    valid = [r for r in records if r['content'].strip()]
    if valid:
        push_to_searchdb(valid, "bynr_sthj")
    return len(valid)

if __name__ == '__main__':
    inc = '--incremental' in sys.argv
    cnt = run(incremental=inc)
    print(f"Done: {cnt} records")
