#!/usr/bin/env python3
"""
安徽颍上县 - 环评公示 (ahys.gov.cn)
列表: AJAX /OpennessTarget/677/52615/page_{n}.html
详情: /OpennessContent/show/{id}.html
正文: div#zoom (g-detailbox)
"""
import sys, os, re, time
from datetime import datetime, timezone, timedelta
import requests, urllib3
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from crawler_lib import push_to_searchdb
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)

SITE_NAME = "安徽颍上县-环评公示"
BASE_URL = "https://www.ahys.gov.cn"
LIST_API = "/OpennessTarget/677/52615/page_{}.html"
THREE_YEARS_AGO = (datetime.now(timezone.utc) - timedelta(days=365*3)).strftime("%Y-%m-%d")
MAX_PAGES = 3
HEADERS = {"User-Agent": "Mozilla/5.0", "X-Requested-With": "XMLHttpRequest"}

def fetch(url):
    try:
        r = requests.get(url, headers=HEADERS, timeout=20, verify=False)
        r.encoding = 'utf-8'
        return r.text
    except: return None

def parse_list(html):
    items = []
    pattern = r'<a[^>]*href="(/OpennessContent/show/\d+\.html)"[^>]*>(.*?)</a>'
    for m in re.finditer(pattern, html, re.DOTALL):
        href = m.group(1)
        title = re.sub(r'<[^>]+>', '', m.group(2)).strip()
        if not title or len(title) < 5: continue
        items.append((title, BASE_URL + href))
    return items

def fetch_detail(url):
    html = fetch(url)
    if not html: return None, None, None
    result = {}
    m = re.search(r'<div[^>]*class="text-center u-title"[^>]*>(.*?)</div>', html, re.DOTALL)
    if m: result["title"] = re.sub(r"<[^>]+>", "", m.group(1)).strip()
    if not result.get("title"):
        m = re.search(r'<h1[^>]*>(.*?)</h1>', html, re.DOTALL)
        if m: result["title"] = re.sub(r"<[^>]+>", "", m.group(1)).strip()
    m = re.search(r'发布时间[：:]\s*(\d{4}-\d{1,2}-\d{1,2})', html)
    if m: result["publish_date"] = m.group(1)
    if not result.get("publish_date"):
        m = re.search(r'<meta[^>]*name="PubDate"[^>]*content="(\d{4}-\d{1,2}-\d{1,2})', html)
    # 正文: m-detailbox（含左侧正文+右侧附件栏）
    m = re.search(r'class="m-detailbox"[^>]*>', html)
    if m:
        content = html[m.end():]
        depth = 0
        for i, c in enumerate(content):
            if content[i:i+4] == '<!--':
                end = content.find('-->', i+4)
                if end > i: i = end + 3
                continue
            if content[i:i+6] == '</div>':
                if depth == 0:
                    content = content[:i].strip()
                    break
                depth -= 1
            elif content[i:i+4] == '<div' and content[i+4] in (' ', '>'):
                depth += 1
        content_str = content if isinstance(content, str) else ''
        m2 = re.search(r'class="row[^"]*"[^>]*>(.*)', content_str, re.DOTALL)
        if m2:
            content_str = m2.group(1)
        content_str = re.sub(r"<script[^>]*>.*?</script>", "", content_str, flags=re.DOTALL|re.I)
        content_str = re.sub(r"<style[^>]*>.*?</style>", "", content_str, flags=re.DOTALL|re.I)
        if len(content_str) > 100:
            result["content"] = content_str
    if not result.get("content"):
        for cls in ['g-detailbox', 'content', 'article', 'text']:
            m = re.search(r'<(div|section)[^>]*class="' + cls + r'[^"]*"[^>]*>(.*?)</\1>', html, re.DOTALL)
            if m and len(m.group(2)) > 100:
                result["content"] = m.group(2).strip()
                break
    return result.get("title"), result.get("content"), result.get("publish_date")

def main():
    print(f"\n{'='*50}\n🏠 {SITE_NAME}\n{'='*50}")
    all_list = []
    for page in range(1, MAX_PAGES+1):
        url = BASE_URL + LIST_API.format(page)
        print(f"\n📄 第 {page} 页...", end=" ", flush=True)
        html = fetch(url)
        if not html: print("❌"); break
        items = parse_list(html)
        if not items: print("0 条"); break
        print(f"✅ {len(items)} 条")
        all_list.extend(items)
    print(f"\n📊 列表总计: {len(all_list)} 条")
    all_items, seen = [], set()
    for i, (title, url) in enumerate(all_list):
        if "项目" not in title: continue
        if url in seen: continue
        seen.add(url)
        print(f"  [{i+1}/{len(all_list)}] {title[:50]}...", end=" ", flush=True)
        dt, content, date = fetch_detail(url)
        if dt: title = dt
        summary = re.sub(r"<[^>]+>", " ", content or "").strip()[:300]
        summary = re.sub(r"\s+", " ", summary)
        all_items.append({
            "site_name": SITE_NAME, "title": title, "url": url,
            "content": content or "", "pub_date": date or "",
            "summary": summary, "tags": SITE_NAME,
        })
        print("✅")
        time.sleep(0.3)
    if all_items:
        push_to_searchdb(all_items, "ahys_hpgs")
    print(f"\n✅ 完成! 共 {len(all_items)} 条")

if __name__ == "__main__":
    t0 = time.time()
    main()
    print(f"⏱ 耗时: {time.time()-t0:.1f}s")
