#!/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.yjq.gov.cn"
API_URL = f"{BASE_URL}/wuhu/site/label/8888"
API_DATA = {
    "labelName": "grassrootsContentPageList",
    "siteId": "6787891",
    "organId": "6603431",
    "pageSize": "15",
    "pageIndex": "1",
    "isDate": "true",
    "dateFormat": "yyyy-MM-dd",
    "length": "50",
    "type": "4",
    "action": "list",
    "isJson": "true",
    "catId": "1000161",
}
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 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 j-fontContent gkwz_contnet
    idx = html.find('class="j-fontContent gkwz_contnet"')
    if idx < 0:
        idx = html.find("gkwz_contnet")
    if idx >= 0:
        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] == "<" and html[j+1:j+2] != "/":
                pass
            elif 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:
                        result["content"] = html[start:tag_end+1]
                        break
        else:
            result["content"] = html[idx:idx+5000]

    # Extract clean text from content HTML
    if result["content"]:
        result["content"] = extract_clean_text(result["content"])

    return result


def extract_clean_text(content_html):
    """Clean HTML to text with markdown links."""
    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)
        md = f"[{text}]({full_url})"
        a_tag.replace_with(md)

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

    parts = []
    # Extract tables as HTML
    for table in soup.find_all('table'):
        parts.append(str(table))
    # Extract paragraph text
    for p in soup.find_all('p'):
        t = p.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})")

    # 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)):  # safety cap
        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")

    # Fetch details
    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", [])
    filtered = [it for it in items if (it.get("publishDate") or "")[:10] >= cutoff]

    enriched = []
    for item in filtered:
        url = item.get("urlDomain", "")
        html, _ = fetch_detail(item["contentId"])
        detail = parse_detail(html) if html else {"title": "", "publish_date": "", "content": ""}
        enriched.append({
            "title": detail["title"] or item.get("title", ""),
            "page_url": url,
            "publish_date": (item.get("publishDate") or "")[:10],
            "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]}")
