#!/usr/bin/env python3
import os
"""
灵石县 - 通知公告 (lingshi.gov.cn)
列表: /xwzx/tzgg → /xwzx/tzgg_{N} (N=2..14, 10条/页, 共132条)
详情: /xwzx/tzgg/content_XXXXX
正文: div.conTxt
"""
import re, sys, os, json, time
import urllib.request, urllib.error
from bs4 import BeautifulSoup
import sqlite3

BASE_URL = "http://www.lingshi.gov.cn"
FETCH_BASE = "http://218.26.234.211"
SITE_NAME = "灵石县-通知公告"
GROUP_NAME = "山西"
DB = os.environ.get("SEARCH_DB", "/root/search.db")
HEADERS = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36",
    "Host": "www.lingshi.gov.cn",
}

_MAX_PG = None
for i, a in enumerate(sys.argv):
    if a == "--pages" and i + 1 < len(sys.argv):
        _MAX_PG = int(sys.argv[i + 1])
        break


def fetch(url):
    url = url.replace(BASE_URL, FETCH_BASE)
    req = urllib.request.Request(url, headers=HEADERS)
    try:
        return urllib.request.urlopen(req, timeout=30).read().decode("utf-8", errors="replace")
    except Exception as e:
        print(f"[WARN] fetch failed: {url} - {e}", file=sys.stderr)
        return ""


def extract_items(html):
    """Extract items from list page"""
    items = []
    soup = BeautifulSoup(html, "html.parser")
    for a in soup.find_all("a", href=True):
        href = a["href"]
        text = a.get_text(strip=True)
        if "content_" not in href or len(text) < 10:
            continue
        if not href.startswith("http"):
            href = BASE_URL + href if href.startswith("/") else BASE_URL + "/xwzx/tzgg/" + href
        fetch_href = href.replace(BASE_URL, FETCH_BASE)
        # Find date - it's usually in the parent LI or nearby
        date = ""
        parent = a.find_parent("li")
        if parent:
            span = parent.find("span")
            if span:
                date = span.get_text(strip=True)
        items.append({"title": text, "url": fetch_href, "orig_url": href, "date": date})
    return items


def parse_detail(html, url):
    """Parse detail page"""
    soup = BeautifulSoup(html, "html.parser")

    title = ""
    meta = soup.find("meta", attrs={"name": "ArticleTitle"})
    if meta and meta.get("content"):
        title = meta["content"].strip()

    date_text = ""
    meta = soup.find("meta", attrs={"name": "PubDate"})
    if meta and meta.get("content"):
        m = re.search(r"(\d{4}-\d{2}-\d{2})", meta["content"])
        if m:
            date_text = m.group(1)

    content = ""
    attachments = []
    content_div = soup.select_one("div.conTxt")
    if not content_div:
        return {"title": title, "date": date_text, "content": "", "attachments": []}

    parts = []
    for el in content_div.find_all(["p", "table", "img"], recursive=True):
        if el.name == "p" and el.find_parent("table"):
            continue
        if el.name == "table" and el.find_parent("table"):
            continue

        if el.name == "img":
            src = el.get("src", "")
            if "icon_" in src.lower() or "/sysimage/" in src.lower():
                continue
            alt = el.get("alt", "") or ""
            if src.startswith("//"):
                src = "http:" + src
            elif src.startswith("/"):
                src = BASE_URL + src
            elif not src.startswith("http"):
                src = url.rsplit("/", 1)[0] + "/" + src
            parts.append(f"![{alt}]({src})")
            continue

        if el.name == "table":
            rows = []
            for tr in el.find_all("tr"):
                cols = []
                for cell in tr.find_all(["td", "th"]):
                    cell_text = cell.get_text(" ", strip=True)
                    for a in cell.find_all("a", href=True):
                        ahref = a["href"]
                        if re.search(r'\.(docx?|pdf|xlsx?|rar|zip)$', ahref, re.I):
                            atitle = a.get_text(strip=True) or a.get("download", "")
                            if ahref.startswith("/"):
                                ahref = BASE_URL + ahref
                            elif not ahref.startswith("http"):
                                ahref = url.rsplit("/", 1)[0] + "/" + ahref
                            attachments.append({"title": atitle or "附件", "url": ahref})
                    cols.append(cell_text)
                if cols:
                    rows.append("| " + " | ".join(cols) + " |")
            if rows:
                col_count = len(rows[0].split("|")) - 2
                sep = "| " + " | ".join(["---"] * col_count) + " |"
                rows.insert(1, sep)
                parts.append("\n".join(rows))
            continue

        text = el.get_text(" ", strip=True)
        if text:
            for a in el.find_all("a", href=True):
                ahref = a["href"]
                if re.search(r'\.(docx?|pdf|xlsx?|rar|zip)$', ahref, re.I):
                    atitle = a.get_text(strip=True) or a.get("download", "")
                    if ahref.startswith("/"):
                        ahref = BASE_URL + ahref
                    elif not ahref.startswith("http"):
                        ahref = url.rsplit("/", 1)[0] + "/" + ahref
                    attachments.append({"title": atitle or "附件", "url": ahref})
            parts.append(text)

    content = "\n\n".join(p for p in parts if p.strip())
    content = content.replace("\u00a0", " ").replace("&nbsp;", " ")

    seen = set()
    unique_att = []
    for att in attachments:
        if att["url"] not in seen:
            seen.add(att["url"])
            unique_att.append(att)

    return {"title": title, "date": date_text, "content": content, "attachments": unique_att}


def main():
    conn = sqlite3.connect(DB)
    c = conn.cursor()

    # Clean old data
    c.execute("DELETE FROM gov_search WHERE site_name=?", (SITE_NAME,))
    c.execute("DELETE FROM gov_raw WHERE site_name=?", (SITE_NAME,))
    conn.commit()
    print("[清理] 已清理该站旧数据", flush=True)

    all_items = []

    # Page 1
    html = fetch(f"{BASE_URL}/xwzx/tzgg")
    if not html:
        print("[ERROR] Cannot fetch list page", file=sys.stderr)
        sys.exit(1)
    items = extract_items(html)
    print(f"[INFO] Page 1: {len(items)} items", file=sys.stderr)
    all_items.extend(items)

    # Determine total pages from page 1
    m = re.search(r'共(\d+)页', html)
    total_pages = int(m.group(1)) if m else 14
    if _MAX_PG and total_pages > _MAX_PG:
        total_pages = _MAX_PG
    print(f"[INFO] Total pages: {total_pages}", file=sys.stderr)

    # Pages 2+: /xwzx/tzgg_{N}
    for pg in range(2, total_pages + 1):
        url = f"{BASE_URL}/xwzx/tzgg_{pg}"
        html = fetch(url)
        if not html:
            break
        items = extract_items(html)
        if not items:
            break
        print(f"[INFO] Page {pg}: {len(items)} items", file=sys.stderr)
        all_items.extend(items)

    print(f"[INFO] Total: {len(all_items)} items", file=sys.stderr)

    new_count = 0
    empty_count = 0
    total_att = 0

    for idx, item in enumerate(all_items):
        c.execute("SELECT id FROM gov_raw WHERE page_url=?", (item["orig_url"],))
        if c.fetchone():
            continue

        if idx % 5 == 0:
            print(f"[INFO] [{idx}/{len(all_items)}] {item['title'][:40]}...", file=sys.stderr, end=" ", flush=True)

        html = fetch(item["url"])
        if not html:
            if idx % 5 == 0:
                print("FETCH FAILED", file=sys.stderr)
            continue

        detail = parse_detail(html, item["url"])
        title = detail["title"] or item["title"]
        date_text = detail["date"] or item["date"]
        content = detail["content"]
        attachments = detail["attachments"]

        if not content.strip():
            empty_count += 1
            if idx % 5 == 0:
                print("EMPTY", file=sys.stderr)
            continue

        plain = re.sub(r'\s+', ' ', content).strip()
        summary = plain[:200] if plain else title[:200]
        att_json = json.dumps(attachments, ensure_ascii=False) if attachments else "[]"

        date_rank = 0
        if date_text:
            m2 = re.search(r"(\d{4})-(\d{2})-(\d{2})", date_text)
            if m2:
                date_rank = int(m2.group(1) + m2.group(2) + m2.group(3))

        try:
            c.execute(
                """INSERT OR IGNORE INTO gov_raw 
                (title, site_name, group_name, page_url, publish_date, content, summary, attachments, date_rank)
                VALUES (?,?,?,?,?,?,?,?,?)""",
                (title, SITE_NAME, GROUP_NAME, item["orig_url"], date_text, content, summary, att_json, date_rank)
            )
            if c.rowcount > 0:
                new_count += 1
                total_att += len(attachments)
        except Exception as e:
            if idx % 5 == 0:
                print(f"DB ERROR: {e}", file=sys.stderr)

        time.sleep(0.3)

    conn.commit()
    conn.close()

    print(f"\n[RESULT] {SITE_NAME}: {new_count} new, {empty_count} empty, {total_att} attachments")


if __name__ == "__main__":
    main()
