#!/usr/bin/env python3
"""crawl_cangzhou_sthj.py - 沧州市人民政府-生态环境 (table列表 + 详情div.detail)"""
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.cangzhou.gov.cn/cangzhou/c100558'

def fetch_urls_from_page(page_num):
    if page_num == 0:
        url = BASE + '/list.shtml'
    else:
        url = f'{BASE}/list_{page_num + 1}.shtml'
    try:
        r = requests.get(url, timeout=(5, 15), headers=HEADERS, verify=False)
        r.encoding = 'utf-8'
    except:
        return []
    # table 条目: <tr><td>序号</td><td><a href="...">标题</a></td>...<td>日期</td></tr>
    trs = re.findall(r'<tr[^>]*>(.*?)</tr>', r.text, re.DOTALL)
    results = []
    for tr in trs:
        a = re.search(r'<a[^>]*href="([^"]+)"[^>]*>(.*?)</a>', tr, re.DOTALL)
        if not a:
            continue
        title = re.sub(r'<[^>]+>', '', a.group(2)).strip()
        if len(title) < 4:
            continue
        d = re.search(r'(\d{4}-\d{2}-\d{2})', tr)
        pub_date = d.group(1) if d else ''
        href = a.group(1)
        if href.startswith('/'):
            full_url = 'https://www.cangzhou.gov.cn' + href
        elif href.startswith('./'):
            full_url = BASE + href[1:]
        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(3):
        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'<h1[^>]*>(.*?)</h1>', r.text, re.DOTALL)
    if m:
        title = re.sub(r'<[^>]+>', '', m.group(1)).strip()
    if not title:
        m = re.search(r'<title>([^<]*)</title>', r.text, re.DOTALL)
        if m:
            title = re.sub(r'<[^>]+>', '', m.group(1)).strip()
            title = re.sub(r'\s*[-_|_].*$', '', title).strip()
    content = ''
    idx = r.text.find('<div class="file_detail"')
    if idx > 0:
        start = r.text.find('>', idx) + 1
        depth = 1
        pos = start
        while pos < len(r.text) and depth > 0:
            if r.text[pos:pos+4] == '<div':
                depth += 1
                pos += 4
            elif r.text[pos:pos+6] == '</div>':
                depth -= 1
                pos += 6
            else:
                pos += 1
        content = r.text[start:pos-6].strip()
    return title, content

def run(incremental=False):
    records = []
    seen = set()
    max_pages = 1 if incremental else 15
    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'] 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 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, "cangzhou_sthj")
    return len(valid)

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