#!/usr/bin/env python3
"""
Crawler: 芒市人民政府 - 征集调查 (昆明慧软 CMS)
List: /Web/zjdcindex.do?page=N
Detail: /Web/_F0_0_XXXX.htm
Content div: div.content
"""
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 = "https://www.dhms.gov.cn"
HEADERS = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.0.0 Safari/537.36",
}
MAX_PAGES = 5


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


def fetch_list_page(page_no):
    if page_no == 1:
        url = f"{BASE_URL}/Web/zjdcindex.do"
    else:
        url = f"{BASE_URL}/Web/zjdcindex.do?page={page_no}"
    try:
        r = requests.get(url, headers=HEADERS, timeout=30, verify=False)
        r.encoding = "utf-8"
        return r.text
    except Exception as e:
        log(f"List page {page_no} error: {e}")
        return None


def parse_list_page(html):
    """Extract (title, url, date) tuples."""
    items = []
    soup = BeautifulSoup(html, "html.parser")
    # Find all li elements with leftboxula links
    for a_tag in soup.find_all("a", class_="leftboxula"):
        title = a_tag.get_text(strip=True)
        url = a_tag.get("href", "")
        # Find the date span that follows this link
        span = a_tag.find_next_sibling("span")
        date = span.get_text(strip=True) if span else ""
        if title and url and date:
            items.append((title, url, date))
    return items


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


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

    # Title from h1 in contitle div
    contitle = soup.find("div", class_="contitle")
    if contitle:
        h1 = contitle.find("h1")
        if h1:
            result["title"] = h1.get_text(strip=True)
    if not result["title"]:
        meta = soup.find("meta", attrs={"name": "title"}) or soup.find("title")
        if meta:
            result["title"] = meta.get("content", "") or meta.get_text(strip=True)

    # Date from meta PubDate
    meta_date = soup.find("meta", attrs={"name": "PubDate"})
    if meta_date and meta_date.get("content"):
        result["publish_date"] = meta_date["content"].replace("/", "-")[:10]
    if not result["publish_date"]:
        date_span = soup.find("span", string=re.compile(r"日期"))
        if date_span:
            m = re.search(r"(\d{4}/\d{1,2}/\d{1,2})", date_span.get_text())
            if m:
                result["publish_date"] = m.group(1).replace("/", "-")

    # Content from div.content (main content area, not nav/sidebar)
    content_div = soup.find("div", class_="content")
    if content_div:
        result["content"] = extract_clean_text(str(content_div))
    else:
        page_main = soup.find("div", class_="contentbox")
        if page_main:
            content_div = page_main.find("div", class_=lambda c: c and "content" in c.split() if c else False)
            if content_div:
                result["content"] = extract_clean_text(str(content_div))

    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})")

    all_items = []
    for pg in range(1, MAX_PAGES + 1):
        html = fetch_list_page(pg)
        if not html:
            break
        items = parse_list_page(html)
        if not items:
            log(f"  Page {pg}: empty, stopping")
            break
        dates = [d for _, _, d in items]
        all_before = all(d < cutoff for d in dates)
        if all_before:
            log(f"  Page {pg}: all before cutoff, stopping")
            break
        for title, url, date in items:
            if date < cutoff:
                continue
            all_items.append({"title": title, "url": url, "date": date})
        log(f"  Page {pg}: {len(items)} items (accumulated: {len(all_items)})")
        time.sleep(0.5)

    log(f"After filter: {len(all_items)} items")

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

        enriched.append({
            "title": item["title"],
            "page_url": item["url"],
            "publish_date": item["date"],
            "content": item.get("content", ""),
            "site_name": f"{SITE}-{COLUMN}",
            "column": COLUMN,
        })
        if idx % 10 == 0:
            log(f"  Detail: {idx}/{len(all_items)}")
        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_page(1)
    if not html:
        return
    items = parse_list_page(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_page(1)
        items = parse_list_page(html) if html else []
        log(f"Page 1: {len(items)} items")
        for t, u, d in items[:5]:
            print(f"  {d} | {t[:60]}")
