#!/usr/bin/env python3
"""crawl_luohe_hpnspgs.py - 漯河市生态环境局-环评拟审批公示

站点: https://sthjj.luohe.gov.cn/xxgk/hjyxpj/jsxmhjyxpj/hpnspgs
CMS: PowerCMS (UTF-8, power.css/webcommon.js)
列表: li > span.date(YYYY-MM-DD) + a[title="标题：xxx&#xD;&#xA;点击数：N&#xD;&#xA;发表时间：date"]
      详情 href=/xxgk/hjyxpj/jsxmhjyxpj/hpnspgs/content_XXXXXXX
分页: 静态分页 hpnspgs_N (首页无后缀, 第2页=hpnspgs_2, 每页10条, 共33页/322条)
详情: h2.title 完整标题 + div.conTxt 正文(含表格, 平衡div匹配)
      时间: 列表 span.date / 详情 发布时间：YYYY-MM-DD
附件: 正文内无附件(公共导航"申请表格下载"在conTxt外, 自动排除)
标题: strip &middot;&nbsp; 实体前缀; 列表title属性优先(完整), fallback链接文本
"""
import sys, os, re, argparse
import requests
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) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0 Safari/537.36'
}
BASE = 'https://sthjj.luohe.gov.cn'
LIST_PATH = 'xxgk/hjyxpj/jsxmhjyxpj/hpnspgs'


def fetch_list(page_idx):
    if page_idx == 1:
        url = f'{BASE}/{LIST_PATH}'
    else:
        url = f'{BASE}/{LIST_PATH}_{page_idx}'
    try:
        r = requests.get(url, timeout=(5, 15), headers=HEADERS, verify=False)
        r.encoding = 'utf-8'
    except Exception:
        return []
    items = re.findall(
        r'<span class="date">(\d{4}-\d{2}-\d{2})</span>\s*<a href="([^"]*content_\d+)"[^>]*title="([^"]*)"[^>]*>(.*?)</a>',
        r.text, re.DOTALL
    )
    results = []
    for pd, href, title_attr, link_text in items:
        # 标题: 优先 title 属性中"标题："后的完整标题, fallback 链接文本
        title = ''
        m = re.search(r'标题[：:]\s*(.*?)(?:&#xD;|&#13;|$)', title_attr, re.DOTALL)
        if m:
            title = m.group(1).strip()
        if not title or len(title) < 4:
            title = re.sub(r'<[^>]+>', '', link_text).strip()
        # strip &middot;&nbsp; 实体前缀
        title = title.strip()
        title = re.sub(r'^\s*(?:&middot;|&nbsp;|·|\s)+', '', title)
        title = re.sub(r'\s+', ' ', title).strip()
        if len(title) < 4:
            continue
        url = BASE + href
        results.append({'url': url, 'pub_date': pd, 'title': title})
    return results


def extract_balanced_div(html, open_tag_re):
    """平衡 div 匹配: 从匹配到的 <div...> 的 '>' 之后, 到对应 </div>, 返回内部 HTML。
    修复非贪婪 (.*?)</div> 在正文含嵌套 div(表格/附件区)时截断的问题"""
    m = re.search(open_tag_re, html)
    if not m:
        return ''
    gt = html.find('>', m.start())
    if gt == -1:
        return ''
    i = gt + 1
    depth = 1
    for mm in re.finditer(r'<div[\s>]|</div>', html[i:]):
        if mm.group(0).startswith('<div'):
            depth += 1
        else:
            depth -= 1
            if depth == 0:
                return html[i:i + mm.start()]
    return html[i:]


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 Exception:
            r = None
    if r is None:
        return '', ''
    # 标题: h2.title (完整标题), strip &middot;&nbsp; 前缀
    title = ''
    m = re.search(r'<h2[^>]*class="[^"]*title[^"]*"[^>]*>(.*?)</h2>', r.text, re.DOTALL)
    if m:
        title = re.sub(r'<[^>]+>', '', m.group(1)).strip()
        title = re.sub(r'^\s*(?:&middot;|&nbsp;|·|\s)+', '', title)
        title = re.sub(r'\s+', ' ', title).strip()
    # 正文: div.conTxt 平衡匹配 (含表格)
    content = ''
    c = extract_balanced_div(r.text, r'<div[^>]*class="[^"]*conTxt[^"]*"[^>]*>')
    if c.strip():
        content = c.strip()
    if not content.strip():
        c = extract_balanced_div(r.text, r'id="content"[^>]*>')
        if c.strip():
            content = c.strip()
    content = re.sub(r'<script.*?</script>', '', content, flags=re.DOTALL | re.I)
    content = re.sub(r'<style.*?</style>', '', content, flags=re.DOTALL | re.I)
    # href/src 相对路径转绝对
    content = re.sub(r'href="(?!https?://|//|#|javascript:)([^"]+)"',
                     lambda mm: f'href="{BASE}{mm.group(1)}"' if mm.group(1).startswith('/') else f'href="{BASE}/{mm.group(1)}"',
                     content)
    content = re.sub(r'src="(?!https?://|//)([^"]+)"',
                     lambda mm: f'src="{BASE}{mm.group(1)}"' if mm.group(1).startswith('/') else f'src="{BASE}/{mm.group(1)}"',
                     content)
    # 清首尾空 p (允许带属性)
    content = re.sub(r'^(<p[^>]*>(\s*(<br\s*/?>)?\s*)?</p>)+', '', content)
    content = re.sub(r'(<p[^>]*>(\s*(<br\s*/?>)?\s*)?</p>)+$', '', content)
    return title, content.strip()


def run(max_pages=5):
    records = []
    seen = set()
    for pg in range(max_pages):
        items = fetch_list(pg + 1)
        if not items:
            print(f"  Page {pg + 1}: 0 items (stop)")
            break
        print(f"  Page {pg + 1}: {len(items)} items")
        for it in items:
            if it['pub_date'] and it['pub_date'] < CUTOFF:
                continue
            if it['url'] in seen:
                continue
            seen.add(it['url'])
            title, content = fetch_detail(it['url'])
            if not title:
                title = it['title']
            if not content.strip():
                print(f"    SKIP empty content: {it['url']}")
                continue
            records.append({
                'title': title, 'url': it['url'], 'source_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, "luohe_hpnspgs")
    return len(valid)


if __name__ == '__main__':
    ap = argparse.ArgumentParser()
    ap.add_argument('--pages', type=int, default=5)
    args = ap.parse_args()
    cnt = run(max_pages=args.pages)
    print(f"Done: {cnt} records")
