#!/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 = "安徽蚌埠"
PER_PAGE = 20
MAX_PAGES = 5
BASE_URL = "https://www.wuhe.gov.cn"
LIST_API = "https://www.wuhe.gov.cn/content/column/30602871"

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 list page"""
    items = []
    pattern = r'<li\s+class="(odd|even)">\s*<span\s+class="right\s+date">(\d{4}-\d{1,2}-\d{1,2})</span>\s*<a[^>]+href="([^"]+)"[^>]*title="([^"]*)"'
    for m in re.finditer(pattern, html):
        date = m.group(2).strip()
        url = m.group(3).strip()
        title = m.group(4).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 from h1.newstitle
    title = ""
    h1 = soup.find('h1', class_='newstitle')
    if h1:
        title = h1.get_text(strip=True)

    # Date from newsinfo span
    date = ""
    ni = soup.find('div', class_='newsinfo')
    if ni:
        dm = re.search(r'(\d{4}-\d{1,2}-\d{1,2})', ni.get_text())
        if dm:
            date = dm.group(1)

    # Body from div.newscontnet
    body = ""
    nc = soup.find('div', class_='newscontnet')
    if nc:
        paras = [p.get_text(strip=True) for p in nc.find_all('p') if p.get_text(strip=True)]
        body = '\n\n'.join(paras)

    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)
                VALUES (?, ?, ?, ?, ?, ?, ?)""",
                (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()
    max_pages = args.max_pages

    all_items = []

    for page in range(1, max_pages + 1):
        url = "{}?pageIndex={}".format(LIST_API, page)
        try:
            html = fetch(url)
            items = extract_list(html)
            if not items:
                print("Page {}: empty, stopping".format(page))
                break
            all_items.extend(items)
            print("Page {}: {} items".format(page, len(items)))
        except Exception as e:
            print("Page {} error: {}".format(page, e))
            break
        time.sleep(0.5)

    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
    timeout_count = 0
    error_count = failed
    abnormal_count = 0
    print("\n=== Summary ===")
    print("{} | {} | {} | {} | {}".format(SITE_NAME, inserted, timeout_count, error_count, abnormal_count))

if __name__ == "__main__":
    main()
