#!/usr/bin/env python3
"""
Crawler: 南陵县人民政府 - 建设项目环评文件（报告书、报告表）审批 (Epoint 基层政务公开)
"""
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.nlx.gov.cn"
API_URL = f"{BASE_URL}/wuhu/site/label/8888"
API_DATA = {
    "labelName": "grassrootsContentPageList",
    "siteId": "6787891",
    "organId": "6603411",
    "pageSize": "15",
    "pageIndex": "1",
    "isDate": "true",
    "dateFormat": "yyyy-MM-dd",
    "length": "50",
    "type": "4",
    "action": "list",
    "isJson": "true",
    "catId": "1003011",
}
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",
    "Accept": "application/json, text/plain, */*",
    "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",
}
ATTACH_EXTS = ('.doc', '.docx', '.pdf', '.xls', '.xlsx', '.ppt', '.pptx', '.zip', '.rar', '.7z')


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


def fetch_list_page(page_index):
    """Fetch one page of list data from API."""
    data = {**API_DATA, "pageIndex": str(page_index)}
    try:
        r = requests.post(API_URL, data=data, headers=HEADERS, timeout=30, verify=False)
        return r.json()
    except Exception as e:
        log(f"API error: {e}")
        return None


def get_content_local(html):
    """Extract content from nlx.gov.cn - j-fontContent gkwz_contnet div."""
    idx = html.find('class="j-fontContent gkwz_contnet"')
    if idx < 0:
        idx = html.find("gkwz_contnet")
    if idx < 0:
        return ""
    start = html.rfind("<", 0, idx)
    depth = 1
    j = html.find(">", idx)
    while depth > 0 and j < len(html):
        j += 1
        if html[j:j+4] == "<!--":
            k = html.find("-->", j)
            if k >= 0:
                j = k + 3
                continue
        if html[j:j+2] == "</":
            tag_end = html.find(">", j)
            if tag_end > j:
                tag_name = html[j+2:tag_end].split()[0]
                if tag_name and tag_name != "div":
                    j = tag_end
                    continue
                depth -= 1
                if depth == 0:
                    return _clean_content(html[start:tag_end+1])
    return ""


def _clean_content(content_html):
    """Convert content HTML to clean text with markdown links, preserving tables as HTML in original position."""
    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 fetch_detail(content_id):
    """Fetch detail page and extract content."""
    url = f"{BASE_URL}/grassroots/content/{content_id}"
    try:
        r = requests.get(url, headers=HEADERS, timeout=30, verify=False)
        r.encoding = "utf-8"
        return r.text, url
    except Exception as e:
        log(f"Fetch error for {content_id}: {e}")
        return None, url


def parse_detail(html):
    """Extract title, date, content from detail page."""
    result = {"title": "", "publish_date": "", "content": ""}

    # Title from <title>
    m = re.search(r'<title>(.*?)</title>', html)
    if m:
        title = m.group(1).strip()
        title = re.sub(r'[_\-—]\s*芜湖市政务公开平台\s*$', '', title).strip()
        result["title"] = title

    # Date from meta PubDate
    m = re.search(r'PubDate.*?content="([^"]+)"', html)
    if m:
        result["publish_date"] = m.group(1).strip()[:10]

    # Content from detail page
    content = get_content_local(html)
    result["content"] = content

    return result


def crawl_all(months_back=36):
    cutoff = (datetime.now() - timedelta(days=months_back * 30)).strftime("%Y-%m-%d")
    log(f"Full crawl (cutoff: {cutoff})")

    # Get total from page 1
    data = fetch_list_page(1)
    if not data:
        log("Failed to fetch page 1")
        return
    total = data.get("total", 0)
    page_size = int(API_DATA["pageSize"])
    total_pages = (total + page_size - 1) // page_size
    log(f"Total: {total}, pages: {total_pages}")

    all_items = []
    for pg in range(1, min(total_pages + 1, 501)):
        data = fetch_list_page(pg)
        if not data:
            break
        items = data.get("data", [])
        for item in items:
            pub_date = (item.get("publishDate") or "")[:10]
            if pub_date < cutoff:
                continue
            all_items.append({
                "content_id": item["contentId"],
                "title": item.get("title", ""),
                "date": pub_date,
                "url": item.get("urlDomain", ""),
                "department": item.get("publishDepartment", ""),
            })
        log(f"  Page {pg}: {len(items)} items")
        time.sleep(0.5)

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

    enriched = []
    for idx, item in enumerate(all_items, 1):
        if item["url"]:
            html, _ = fetch_detail(item["content_id"])
            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"] = ""
        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)

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

    data = fetch_list_page(1)
    if not data:
        return
    items = data.get("data", [])

    enriched = []
    for item in items:
        pub_date = (item.get("publishDate") or "")[:10]
        if pub_date < cutoff:
            continue
        url = item.get("urlDomain", "")
        html, _ = fetch_detail(item["contentId"])
        detail = parse_detail(html) if html else {"title": "", "publish_date": "", "content": ""}

        # If no local urlDomain, skip (external links like 办事指南)
        if not url:
            log(f"  Skip external: {item.get('title','')} (no urlDomain)")
            continue

        enriched.append({
            "title": detail["title"] or item.get("title", ""),
            "page_url": url,
            "publish_date": pub_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":
        data = fetch_list_page(1)
        total = data.get("total", 0) if data else 0
        log(f"Total: {total}")
        for it in (data.get("data") or [])[:5]:
            print(f"  {(it.get('publishDate') or '')[:10]} | {it.get('title','')[:60]}")
