#!/usr/bin/env python3
"""
灌南县-公示公告 (www.guannan.gov.cn)
==================================
CMS: TrueCMS with JPage AJAX (API blocked by WAF)
列表: 仅第一页可用 (~60条), #initData > ul.gnzx_ul > li
详情: /gnzx/gsgg/content/{uuid}.html, div.enter 正文
"""
import re, sys, os, time
from datetime import datetime, timedelta, timezone
import requests, urllib3
from bs4 import BeautifulSoup
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)

SITE_NAME  = "灌南县-公示公告"
BASE_URL   = "http://www.guannan.gov.cn/gnzx/gsgg/"
SEARCH_DB = os.getenv("SEARCH_DB", "/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"}


def fetch_list():
    """Fetch first page - only page available (AJAX API blocked)"""
    url = BASE_URL + "gsgg.html"
    try:
        r = requests.get(url, headers=HEADERS, timeout=30)
        r.encoding = "utf-8"
        return r.text
    except Exception as e:
        print("  ! fetch list fail: {}".format(str(e)[:60]))
        return None


def parse_list(html):
    """Extract items from initData div"""
    soup = BeautifulSoup(html, "html.parser")
    items = []
    init = soup.find("div", id="initData")
    if not init:
        return items
    for ul in init.find_all("ul", class_="gnzx_ul"):
        li = ul.find("li")
        if not li:
            continue
        a = li.find("a")
        span = li.find("span")
        if not a or not span:
            continue
        href = a.get("href", "")
        title = a.get("title", "") or a.get_text(strip=True)
        pub_date = span.get_text(strip=True)
        if href.startswith("/"):
            href = "http://www.guannan.gov.cn" + href
        elif not href.startswith("http"):
            href = "http://www.guannan.gov.cn/gnzx/gsgg/" + href
        items.append({"title": title, "url": href, "pub_date": pub_date})
    return items


def fetch_detail(url):
    """Fetch detail - extract content from div.enter"""
    try:
        r = requests.get(url, headers=HEADERS, timeout=30)
        r.encoding = "utf-8"
        soup = BeautifulSoup(r.text, "html.parser")
        enter = soup.find("div", class_="enter")
        if enter:
            # Clean scripts/styles
            for t in enter.find_all(["script", "style"]):
                t.decompose()
            return str(enter)
        return ""
    except Exception as e:
        print("  ! detail fail: {}".format(str(e)[:60]))
        return ""


def to_db(items):
    if not items:
        return 0, 0
    import sqlite3
    db = sqlite3.connect(SEARCH_DB, timeout=60)
    db.execute("PRAGMA journal_mode=WAL")
    db.execute("PRAGMA synchronous=NORMAL")
    ok, fail = 0, 0
    for it in items:
        try:
            db.execute(
                "INSERT OR IGNORE INTO gov_raw "
                "(site_name, title, page_url, content, publish_date, summary, tags) "
                "VALUES (?,?,?,?,?,?,?)",
                (
                    SITE_NAME,
                    (it.get("title") or "")[:500],
                    it.get("url", ""),
                    it.get("content", ""),
                    (it.get("pub_date") or "")[:10],
                    "",
                    "公示公告",
                )
            )
            if db.total_changes > 0:
                ok += 1
            else:
                fail += 1
        except Exception as e:
            fail += 1
    db.commit()
    db.close()
    return ok, fail


def main():
    print("=== {} ===".format(SITE_NAME))
    print("日期阈值: {}".format(CUTOFF))

    html = fetch_list()
    if not html:
        print("无法获取列表页")
        return

    items = parse_list(html)
    if not items:
        print("未解析到列表项")
        return

    print("列表项: {} 条".format(len(items)))

    # Filter by cutoff and dedup
    all_items = []
    seen_urls = set()
    for item in items:
        if item["pub_date"] < CUTOFF:
            continue
        if item["url"] in seen_urls:
            continue
        seen_urls.add(item["url"])
        all_items.append(item)

    print("阈值内: {} 条".format(len(all_items)))

    if not all_items:
        print("无有效记录")
        return

    # Fetch details
    for i, item in enumerate(all_items):
        print("  [{}/{}] {}... ".format(i+1, len(all_items), item["title"][:40]),
              end="", flush=True)
        content = fetch_detail(item["url"])
        item["content"] = content
        print("{} {}B".format(item["pub_date"], len(content)))

    ok, fail = to_db(all_items)
    print("\n=== 完成 ===")
    print("新增: {}, 跳过: {}".format(ok, fail))


if __name__ == "__main__":
    main()
