#!/usr/bin/env python3
"""
Crawler: 玉溪市人民政府 - 环境监管信息公开
List: newDepartmentContentds.jspx?channelId=22142&pageNo=N
Detail: /yxszfxxgk/qyhjxxpl/YYYYMMDD/ID.html
Content div: content-txt content-txt-1
"""
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.yuxi.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 = 50  # safe cap


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


def fetch_list_page(page_no):
    url = f"{BASE_URL}/yxgovfront/newDepartmentContentds.jspx?path=yxszfxxgk&channelId=22142&pageNo={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> with <span><a>...</a></span><span>DATE</span> pattern
    for li in soup.find_all("li"):
        spans = li.find_all("span")
        if len(spans) >= 2:
            a_tag = spans[0].find("a")
            if a_tag and a_tag.get("href"):
                title = a_tag.get_text(strip=True) or a_tag.get("title", "")
                url = a_tag["href"]
                date = spans[1].get_text(strip=True)
                if title and url and date:
                    items.append((title, url, date))
    return items


def fetch_detail(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 h3#zcjd-header
    h3 = soup.find("h3", id="zcjd-header")
    if h3:
        result["title"] = h3.get_text(strip=True)
    if not result["title"]:
        title_tag = soup.find("title")
        if title_tag:
            result["title"] = title_tag.get_text(strip=True)

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

    # Content from content-txt-1 div
    content_div = soup.find("div", class_="content-txt", id="content-txt-1")
    if not content_div:
        content_div = soup.find("div", id="content-txt-1")
    if content_div:
        result["content"] = extract_clean_text(str(content_div))
    else:
        # Fallback: main text area
        pc = soup.find("div", class_="print-container")
        if pc:
            result["content"] = extract_clean_text(str(pc))

    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

        # Check if ALL items are before cutoff (early stop)
        dates = [d for _, _, d in items]
        all_before = all(d < cutoff for d in dates)
        if all_before:
            log(f"  Page {pg}: all {len(items)} items 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 % 20 == 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]}")
