#!/usr/bin/env python3
"""crawl_ablixian_tzgg.py - 理县-通知公告 (nav_list_list容器)"""
import sys, os, requests, re, argparse
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.ablixian.gov.cn'
LIST_URL = '/lxrmzf/c100053/nav_list.shtml'

def fetch_urls_from_page(page_num):
    if page_num > 0:
        return []  # nav_list 首页一次含列表, 分页未确认
    url = BASE + LIST_URL
    try:
        r = requests.get(url, timeout=(5, 15), headers=HEADERS, verify=False)
        r.encoding = 'utf-8'
    except:
        return []
    # 容器: nav_list_list_container > li > a[href title] > p标题 + span日期
    block = r.text
    m = re.search(r'nav_list_list_container(.*?)</ul>', block, re.DOTALL)
    if m:
        block = m.group(1)
    items = re.findall(
        r'<a href="([^"]+)"[^>]*title="([^"]*)"[^>]*>\s*<p>(.*?)</p>\s*<span>(\d{4}-\d{2}-\d{2})</span>',
        block, re.DOTALL
    )
    results = []
    for href, title_attr, title_p, pub_date in items:
        title = title_attr.strip() or re.sub(r'<[^>]+>', '', title_p).strip()
        title = re.sub(r'\s+', '', title)
        if len(title) < 4:
            continue
        if href.startswith('/'):
            full_url = BASE + href
        elif href.startswith('http'):
            full_url = 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 '', ''
    title = ''
    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:
        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*[-_|]\s*理县人民政府\s*$', '', title)
            title = re.sub(r'^\s*理县人民政府\s*[-_|]\s*', '', title)
    title = re.sub(r'\s+', '', title).strip()
    content = ''
    m = re.search(r'class="common_detail"[^>]*>(.*?)</div>', r.text, re.DOTALL)
    if m:
        content = m.group(1).strip()
    return title, content

def run(max_pages=1):
    records = []
    seen = set()
    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:
                title = it['title']
            if 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, "ablixian_tzgg")
    return len(valid)

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