#!/usr/bin/env python3
"""无棣县人民政府-通知公告"""
import re, sys, os, json, time, requests
DB_PATH = os.environ.get("DB_PATH", "/root/search.db")
HEADERS = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36",
    "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8",
    "Accept-Language": "zh-CN,zh;q=0.9",
}
SITE_NAME = "无棣县人民政府-通知公告"
GROUP = "山东滨州"
MAX_PAGES = 3
BASE_URL = "http://www.wudi.gov.cn"
LIST_URL = "http://www.wudi.gov.cn/col/col118240/index.html"

def fetch(url, encoding="utf-8"):
    r = requests.get(url, headers=HEADERS, timeout=30, allow_redirects=True)
    r.encoding = encoding
    return r.text

def resolve_url(rel_url):
    if rel_url.startswith("http"):
        return rel_url
    if rel_url.startswith("/"):
        return BASE_URL + rel_url
    return BASE_URL + "/" + rel_url

def extract_list(html):
    """Extract (title, url, date) from CDATA records"""
    items = []
    records = re.findall(r'<record><!\[CDATA\[(.*?)\]\]></record>', html, re.DOTALL)
    for rec in records:
        m = re.search(r'<a\s+href="([^"]+)"\s+title="([^"]*)".*?</a><span>([^<]+)</span>', rec)
        if m:
            url = m.group(1).strip()
            title = m.group(2).strip()
            date = m.group(3).strip()
            items.append((title, url, date))
    return items

def extract_detail(html):
    """Extract body content from detail page"""
    from bs4 import BeautifulSoup
    soup = BeautifulSoup(html, 'html.parser')

    # Title
    title = ""
    t = soup.find('title')
    if t:
        title = t.get_text(strip=True)
        title = re.sub(r'[_\-].*$', '', title).strip()
        title = re.sub(r'^无棣县人民政府\s+\S+\s+', '', title).strip()

    # Date
    date = ""
    dm = re.search(r'(\d{4}-\d{1,2}-\d{1,2})', html[:3000])
    if dm:
        date = dm.group(1)

    # Body - look for common content containers
    body = ""
    for cls_name in ['news-content', 'article-content', 'content', 'article', 'TRS_UEDITOR', 'trs_editor_view', 'UCAPContent', 'art-content']:
        el = soup.find(class_=cls_name)
        if el:
            paras = [p.get_text(strip=True) for p in el.find_all('p') if p.get_text(strip=True)]
            if paras:
                body = '\n\n'.join(paras)
                break
    if not body:
        # Fallback: try to find a div with substantial text content
        for div in soup.find_all('div'):
            text = div.get_text(strip=True)
            if len(text) > 200:
                paras = [p.get_text(strip=True) for p in div.find_all('p') if p.get_text(strip=True)]
                if paras:
                    body = '\n\n'.join(paras)
                    break

    return title, body, date

def save_to_db(items, site_name, group):
    import sqlite3
    conn = sqlite3.connect(DB_PATH, timeout=60)
    c = conn.cursor()
    inserted = 0
    for title, url, date, body in items:
        try:
            c.execute("""INSERT OR REPLACE INTO gov_raw (page_url, site_name, group_name, title, publish_date, summary, content, script_name) VALUES (?, ?, ?, ?, ?, ?, ?, 'crawl_wudi.py')""",
                (url, site_name, group, title, date, body, body))
            inserted += 1
        except Exception as e:
            print("DB error: {} - {}".format(url, e))
    conn.commit()
    conn.close()
    return inserted

def main():
    import argparse
    parser = argparse.ArgumentParser()
    parser.add_argument('--max-pages', type=int, default=MAX_PAGES)
    args = parser.parse_args()

    all_items = []

    # Only 1 page - data is pre-loaded via CDATA
    html = fetch(LIST_URL)
    items = extract_list(html)
    all_items.extend(items)
    print("Page 1: {} items (from CDATA)".format(len(items)))

    print("\nTotal list items: {}".format(len(all_items)))

    # Fetch details
    detail_items = []
    failed = 0
    for i, (title, rel_url, date) in enumerate(all_items):
        url = resolve_url(rel_url)
        try:
            html = fetch(url)
            d_title, body, d_date = extract_detail(html)
            if not d_date:
                d_date = date
            if not d_title:
                d_title = title
            detail_items.append((d_title, url, d_date, body))
            if (i + 1) % 10 == 0:
                print("  progress: {}/{}".format(i + 1, len(all_items)))
        except Exception as e:
            print("  FAILED: {} - {}".format(url, e))
            failed += 1
        time.sleep(0.3)

    print("\nDetails fetched: {}, failed: {}".format(len(detail_items), failed))

    # Save to DB
    inserted = save_to_db(detail_items, SITE_NAME, GROUP)
    print("Inserted: {}".format(inserted))

    # Summary
    print("\n=== Summary ===")
    print("{} | {} | {} | {} | {}".format(SITE_NAME, inserted, 0, failed, 0))

if __name__ == "__main__":
    main()
