#!/usr/bin/env python3
"""
Crawler: 广灵县人民政府 - 公示公告 (TRS CMS static)
List: /glxrmzfz/gsgg/list.shtml (all items on page 1, 120 items)
Detail: /glxrmzfz/gsgg/YYYYMM/XXX.shtml
Content: div.TRS_Editor > ucapcontent
"""
import sys, os, json, re, time, requests
from datetime import datetime, timedelta
from bs4 import BeautifulSoup
from urllib.parse import urljoin

DB_PATH = os.getenv("SEARCH_DB", "/root/search.db")
SITE = "广灵县人民政府"
COLUMN = "公示公告"
BASE_URL = "http://www.sx-guangling.gov.cn"
LIST_URL = f"{BASE_URL}/glxrmzfz/gsgg/list.shtml"
HEADERS = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36"}


def log(msg):
    print(f"[{SITE}] {msg}", flush=True)


def fetch_list():
    try:
        r = requests.get(LIST_URL, headers=HEADERS, timeout=30)
        r.encoding = "utf-8"
        return r.text
    except Exception as e:
        log(f"List error: {e}")
        return None


def parse_list(html):
    """Extract all (title, url, date) from page."""
    items = []
    soup = BeautifulSoup(html, "html.parser")
    for li in soup.find_all("li", attrs={"data-time": True, "data-url": True}):
        date = li.get("data-time", "")
        rel_url = li.get("data-url", "")
        title = li.get("data-title", "") or li.get_text(strip=True)
        if title and rel_url and date:
            full_url = urljoin(BASE_URL, rel_url)
            items.append((title, full_url, date))
    return items


def fetch_detail(detail_url):
    try:
        r = requests.get(detail_url, headers=HEADERS, timeout=30)
        r.encoding = "utf-8"
        return r.text
    except Exception as e:
        log(f"Detail error: {e}")
        return None


def parse_detail(html):
    result = {"title": "", "publish_date": "", "content": ""}
    soup = BeautifulSoup(html, "html.parser")

    # Title
    title_tag = soup.find("title")
    if title_tag:
        t = title_tag.get_text(strip=True)
        t = re.sub(r"\s*-\s*公示公告\s*-\s*广灵县人民政府\s*$", "", t)
        result["title"] = t

    # Date from meta
    meta_date = soup.find("meta", attrs={"name": "PubDate"})
    if meta_date and meta_date.get("content"):
        result["publish_date"] = meta_date["content"][:10]

    # Content from TRS_Editor > ucapcontent
    editor = soup.find("div", class_="TRS_Editor")
    if editor:
        ucap = editor.find("ucapcontent")
        if ucap:
            result["content"] = extract_clean_text(str(ucap))
        else:
            result["content"] = extract_clean_text(str(editor))
    else:
        # Fallback: body text
        body = soup.find("body")
        if body:
            result["content"] = body.get_text(separator="\n", strip=True)[:2000]

    return result


def extract_clean_text(content_html):
    if not content_html:
        return ""
    soup = BeautifulSoup(content_html, "html.parser")

    for a_tag in soup.find_all("a", href=True):
        href = a_tag.get("href", "")
        text = a_tag.get_text(strip=True) or "附件"
        full_url = urljoin(BASE_URL, href)
        a_tag.replace_with(f"[{text}]({full_url})")

    for tag in soup.find_all(['span', 'b', 'strong', 'font', 'em', 'i', 'u', 's']):
        tag.unwrap()

    parts = []
    for el in soup.find_all(['table', 'p']):
        if el.name == 'table':
            parts.append(str(el))
        elif el.name == 'p' and not el.find_parent('table'):
            t = el.get_text(separator='', strip=True)
            if t:
                parts.append(t)
    return '\n\n'.join(parts) if parts else content_html.strip()


def crawl_all(months_back=36):
    cutoff = (datetime.now() - timedelta(days=months_back * 30)).strftime("%Y-%m-%d")
    log(f"Full crawl (cutoff: {cutoff})")
    html = fetch_list()
    if not html:
        return
    items = parse_list(html)
    log(f"Total from list: {len(items)} items")

    filtered = [it for it in items if it[2] >= cutoff]
    log(f"After filter: {len(filtered)} items")

    enriched = []
    for idx, (title, url, date) in enumerate(filtered, 1):
        html = fetch_detail(url)
        if html:
            detail = parse_detail(html)
            if detail["title"]:
                title = detail["title"]
            if detail["publish_date"]:
                date = detail["publish_date"]
            content = detail["content"]
        else:
            content = ""

        enriched.append({
            "title": title,
            "page_url": url,
            "publish_date": date,
            "content": content,
            "site_name": f"{SITE}-{COLUMN}",
            "column": COLUMN,
        })
        if idx % 20 == 0:
            log(f"  Detail: {idx}/{len(filtered)}")
        time.sleep(0.5)

    stored = 0
    skipped = 0
    import sqlite3
    conn = sqlite3.connect(DB_PATH, timeout=60)
    conn.execute("PRAGMA journal_mode=WAL")
    conn.execute("PRAGMA busy_timeout=10000")
    c = conn.cursor()
    for item in enriched:
        try:
            c.execute(
                "INSERT OR IGNORE INTO gov_raw "
                "(site_name, source_url, page_url, title, publish_date, content, summary, category)"
                " VALUES (?,?,?,?,?,?,?,?)",
                (item["site_name"], item["page_url"], item["page_url"],
                 item["title"], item["publish_date"], item["content"],
                 (item["content"] or "")[:500], item["column"]))
            if c.rowcount > 0:
                stored += 1
            else:
                skipped += 1
        except Exception as e:
            log(f"DB error: {e}")
            skipped += 1
    conn.commit()
    conn.close()
    log(f"Result: {stored} new, {skipped} skipped")


def crawl_incremental():
    cutoff = (datetime.now() - timedelta(days=7)).strftime("%Y-%m-%d")
    log(f"Incremental (since {cutoff})")
    html = fetch_list()
    if not html:
        return
    items = parse_list(html)
    filtered = [(t, u, d) for t, u, d in items if d >= cutoff]

    enriched = []
    for title, url, date in filtered:
        html = fetch_detail(url)
        detail = parse_detail(html) if html else {"title": "", "publish_date": "", "content": ""}
        enriched.append({
            "title": detail["title"] or title,
            "page_url": url,
            "publish_date": date,
            "content": detail["content"],
            "site_name": f"{SITE}-{COLUMN}",
            "column": COLUMN,
        })
        time.sleep(0.5)

    stored = 0
    skipped = 0
    import sqlite3
    conn = sqlite3.connect(DB_PATH, timeout=60)
    conn.execute("PRAGMA journal_mode=WAL")
    conn.execute("PRAGMA busy_timeout=10000")
    c = conn.cursor()
    for item in enriched:
        try:
            c.execute(
                "INSERT OR IGNORE INTO gov_raw "
                "(site_name, source_url, page_url, title, publish_date, content, summary, category)"
                " VALUES (?,?,?,?,?,?,?,?)",
                (item["site_name"], item["page_url"], item["page_url"],
                 item["title"], item["publish_date"], item["content"],
                 (item["content"] or "")[:500], item["column"]))
            if c.rowcount > 0:
                stored += 1
            else:
                skipped += 1
        except Exception as e:
            log(f"DB error: {e}")
            skipped += 1
    conn.commit()
    conn.close()
    log(f"Result: {stored} new, {skipped} skipped")


if __name__ == "__main__":
    mode = sys.argv[1] if len(sys.argv) > 1 else "incremental"
    if mode == "incremental":
        crawl_incremental()
    elif mode == "full":
        crawl_all()
    elif mode == "list":
        html = fetch_list()
        items = parse_list(html) if html else []
        log(f"Page: {len(items)} items")
        for t, u, d in items[:5]:
            print(f"  {d} | {t[:60]}")
