#!/usr/bin/env python3
"""安化县人民政府-信息公开-通知公告 (anhua.gov.cn) 爬虫

CMS: CreatorCMS
编码: GB18030
列表: /16/17/22/default.htm (静态分页: default_N.htm, 11页)
详情: h1标题 + div.nry-text正文 + meta PubDate日期
"""

import os, sqlite3, re, time, requests, sys
from datetime import datetime, timezone, timedelta
from urllib3 import disable_warnings, exceptions
disable_warnings(exceptions.InsecureRequestWarning)

SITE_NAME = "安化县-通知公告"
BASE = "http://www.anhua.gov.cn/16/17/22"
LIST_TPL = "http://www.anhua.gov.cn/16/17/22/default.htm"
LIST_PAGE_TPL = "http://www.anhua.gov.cn/16/17/22/default_%d.htm"
DB_PATH = os.environ.get("DB_PATH", "/root/search.db")
CUTOFF = (datetime.now(timezone.utc) - timedelta(days=365*3)).strftime("%Y-%m-%d")
HEADERS = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36"}
MAX_PAGES = 11

def fetch(url, max_retry=3):
    for att in range(max_retry):
        try:
            r = requests.get(url, headers=HEADERS, timeout=20, verify=False)
            r.encoding = "gb18030"
            if r.status_code == 200:
                return r.text
        except Exception as e:
            if att < max_retry - 1:
                time.sleep(2)
    return None

def parse_list_page(html):
    items = []
    for m in re.finditer(r'<li\b[^>]*>(.*?)</li>', html, re.S):
        li = m.group(1)
        link_m = re.search(r"<a[^>]*href='([^']+)'[^>]*title='([^']*)'", li)
        if not link_m:
            continue
        href = link_m.group(1)
        title = link_m.group(2).strip()
        
        # Only keep content items (href starts with content_)
        if not href.startswith("content_"):
            continue
        if href.startswith("http"):
            full_url = href
        elif href.startswith("/"):
            full_url = "http://www.anhua.gov.cn" + href
        else:
            full_url = BASE + "/" + href
        
        # Date from span
        date_str = ""
        date_m = re.search(r'<span[^>]*>(\d{4}-\d{2}-\d{2})</span>', li)
        if date_m:
            date_str = date_m.group(1)
        
        if date_str and date_str < CUTOFF:
            continue
        
        items.append({"title": title, "url": full_url, "pub_date": date_str})
    return items

def fetch_detail(url):
    html = fetch(url)
    if not html:
        return "", "", ""
    
    # Title from h1
    title = ""
    m = re.search(r'<h1[^>]*>(.*?)</h1>', html)
    if m:
        title = re.sub(r'<[^>]+>', '', m.group(1)).strip()
    if not title:
        m = re.search(r'<title>(.*?)</title>', html)
        if m:
            title = m.group(1).strip()
    
    # Content from nry-text
    content = ""
    m = re.search(r'class="nry-text"[^>]*>(.*?)</div>', html, re.S)
    if m:
        content = m.group(1).strip()
    if not content:
        m = re.search(r'class="ah-wrap-content"[^>]*>(.*?)</div>', html, re.S)
        if m:
            content = m.group(1).strip()
    
    content = re.sub(r'<script[^>]*>.*?</script>', '', content, flags=re.S)
    content = re.sub(r'<style[^>]*>.*?</style>', '', content, flags=re.S)
    
    # Date
    date_str = ""
    m = re.search(r"<meta[^>]*name=\"PubDate\"[^>]*content='(\d{4}-\d{2}-\d{2})", html)
    if m:
        date_str = m.group(1)
    if not date_str:
        m = re.search(r'发布时间[：:]\s*(\d{4}[-/]\d{1,2}[-/]\d{1,2})', html)
        if m:
            date_str = m.group(1).replace("/", "-")
    
    return title, content, date_str

def main():
    test = "--test" in sys.argv
    mode = "TEST" if test else "FULL"
    print(f"\n=== {SITE_NAME} ({mode}) ===", flush=True)
    
    all_items = []
    for pg in range(1, MAX_PAGES + 1):
        url = LIST_TPL if pg == 1 else LIST_PAGE_TPL % pg
        html = fetch(url)
        if not html:
            print(f"  Page {pg}: fetch failed", flush=True)
            break
        items = parse_list_page(html)
        print(f"  Page {pg}: {len(items)} items", flush=True)
        all_items.extend(items)
        if len(items) == 0:
            break
    
    print(f"  Total: {len(all_items)} items within 3yr", flush=True)
    
    if not all_items:
        print("  No items to crawl")
        return
    
    if test:
        all_items = all_items[:5]
    
    conn = None if test else sqlite3.connect(DB_PATH, timeout=60)
    cursor = conn.cursor() if conn else None
    total_new = 0
    done = 0
    
    for i, item in enumerate(all_items):
        print(f"  [{i+1}/{len(all_items)}] {item['title'][:40]}... ", end="", flush=True)
        title, content, pub_date = fetch_detail(item["url"])
        if not title:
            title = item["title"]
        if not pub_date:
            pub_date = item["pub_date"]
        
        if test:
            print(f"title={title[:50]} content={len(content)}B date={pub_date}")
            continue
        
        try:
            cursor.execute(
                "INSERT OR IGNORE INTO gov_raw (site_name, title, page_url, content, publish_date, summary, tags) VALUES (?,?,?,?,?,?,?)",
                (SITE_NAME, title[:500], item["url"], content, pub_date, "", "通知公告"),
            )
            if cursor.rowcount > 0:
                total_new += 1
                print(f"{len(content)}B")
            else:
                print("skip")
        except Exception as e:
            print(f"DB error: {e}")
        
        done += 1
        if done % 30 == 0 and conn:
            conn.commit()
    
    if conn:
        conn.commit()
        conn.execute(
            "INSERT OR REPLACE INTO gov_search(rowid, title, site_name, summary) "
            "SELECT r.rowid, r.title, r.site_name, r.summary "
            "FROM gov_raw r WHERE r.rowid NOT IN (SELECT rowid FROM gov_search) AND r.site_name=?",
            (SITE_NAME,)
        )
        conn.commit()
        c = conn.execute("SELECT COUNT(*) FROM gov_raw WHERE site_name=?", (SITE_NAME,))
        cnt = c.fetchone()[0]
        conn.close()
        print(f"\n=== 完成 ===", flush=True)
        print(f"  新增: {total_new}条", flush=True)
        print(f"  累计: {cnt}条", flush=True)

if __name__ == "__main__":
    main()
