#!/usr/bin/env python3
"""crawl_zhuji_hjsp.py - 诸暨市-建设项目环境影响评价信息公示 (浙江政务服务网)

站点: https://www.zhuji.gov.cn/col/col1229857087/index.html
CMS: jcms 新版(4.5.12.1-ZJSJYH-U39) unitbuild 动态加载 — 列表走API
API: /api-gateway/jpaas-publish-server/front/page/build/unit
     ?parseType=bulidstatic&webId=2745&tplSetId=TM6ldEAz1I8xTXi6VHiB0&pageType=column
     &tagId=右侧list内容&editType=null&pageId=1229857087&paramJson={"pageNo":N,"pageSize":15}
列表: li.cf > a.fl(标题) + span.fr(YYYY-MM-DD)
分页: paramJson pageNo 1..48 (每页15条, 共719条)
详情: h1.wenzhang_content_title / meta[PubDate] + div.wenzhang_content_text 正文
"""
import sys, os, requests, re, argparse, json
from datetime import datetime, timedelta
from urllib.parse import quote

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.zhuji.gov.cn'
API = BASE + '/api-gateway/jpaas-publish-server/front/page/build/unit'
PAGE_SIZE = 15
TOTAL_PAGES = 48

def fetch_list(page_no):
    param_json = json.dumps({"pageNo": page_no, "pageSize": PAGE_SIZE}, ensure_ascii=False)
    params = {
        'parseType': 'bulidstatic', 'webId': '2745',
        'tplSetId': 'TM6ldEAz1I8xTXi6VHiB0', 'pageType': 'column',
        'tagId': '右侧list内容', 'editType': 'null', 'pageId': '1229857087',
        'paramJson': param_json,
    }
    try:
        r = requests.get(API, params=params, timeout=(5, 15), headers=HEADERS, verify=False)
        r.encoding = 'utf-8'
        data = r.json()
        html = data.get('data', {}).get('html', '')
    except Exception as e:
        print(f"    API error: {e}")
        return []
    items = re.findall(
        r'<a class="fl"[^>]*href="([^"]+)"[^>]*>(?:<i[^>]*></i>)?([^<]{2,200})</a>\s*<span class="fr">(\d{4}-\d{2}-\d{2})</span>',
        html, re.DOTALL
    )
    results = []
    for href, title, pd in items:
        title = re.sub(r'\s+', '', title).strip()
        if len(title) < 4:
            continue
        url = href if href.startswith('http') else 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:
            r = None
    if r is None:
        return '', '', ''
    title = ''
    m = re.search(r'<meta name="PubDate" content="([^"]*)"', r.text)
    pd = m.group(1)[:10] if m else ''
    m = re.search(r'<h1[^>]*class="[^"]*wenzhang_content_title[^"]*"[^>]*>(.*?)</h1>', r.text, re.DOTALL)
    if m:
        title = re.sub(r'<[^>]+>', '', m.group(1)).strip()
    if not title:
        m = re.search(r'<title>\s*([^<]+?)\s*</title>', r.text, re.DOTALL)
        if m:
            title = re.sub(r'\s+', '', m.group(1)).strip()
            title = re.split(r'[-–—|_]', title)[0].strip()
    content = ''
    c = extract_balanced_div(r.text, r'<div[^>]*class="[^"]*wenzhang_content_text[^"]*"[^>]*>')
    if c.strip():
        content = c.strip()
    if not content.strip():
        c = extract_balanced_div(r.text, r'<div[^>]*class="[^"]*wenzhang_content[^"]*"[^>]*>')
        if c.strip():
            content = c.strip()
    content = re.sub(r'src="(?!https?://|//)(/[^"]+)"', lambda mm: f'src="{BASE}{mm.group(1)}"', content)
    return title, pd, content

def run(max_pages=5):
    records = []
    seen = set()
    pages = min(max_pages, TOTAL_PAGES)
    for pg in range(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, pd, content = fetch_detail(it['url'])
            if not title:
                title = it['title']
            if not content.strip():
                continue
            records.append({
                'title': title, 'url': it['url'], 'source_url': it['url'],
                'pub_date': pd or 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, "zhuji_hjsp")
    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")
