#!/usr/bin/env python3
import os
"""
重庆化工设计研究院有限公司 - 项目公示 (ccdri.cn)
Portal SaaS (300.cn / 中企动力)
列表: /news/1813122780272599040-{offset}-8.html (offset=0,8,16,24, 每页8条)
详情: /news_details/{id}.html
正文: .e_richText-8 > p
"""
import re, sys, os, json, time
import urllib.request, urllib.error
from bs4 import BeautifulSoup
import sqlite3

BASE_URL = "http://www.ccdri.cn"
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",
}
LIST_URL = "/news/1813122780272599040-{offset}-8.html"
PAGE_SIZE = 8

_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(u):
    req = urllib.request.Request(u, 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: {u} - {e}", file=sys.stderr)
        return ""


def extract_items(html):
    """Extract items from list page HTML"""
    items = []
    soup = BeautifulSoup(html, "html.parser")

    # Find news_detail links
    for a in soup.find_all("a", href=True):
        href = a["href"]
        m = re.search(r"/news_details/(\d+)\.html", href)
        if not m:
            continue

        title = a.get_text(strip=True)
        if not title or len(title) < 5:
            continue

        if not href.startswith("http"):
            href = BASE_URL + href if href.startswith("/") else BASE_URL + "/" + href

        # Date: look for e_timeFormat-11 near this item
        date = ""
        parent = a.find_parent("div", class_=lambda c: c and "cbox" in c)
        if parent:
            time_el = parent.select_one(".e_timeFormat-11")
            if time_el:
                date = time_el.get_text(strip=True)
        if not date:
            # Also check siblings/ancestors
            for p in [a.parent, a.find_parent("div", class_=lambda c: c and "Newscon" in c)]:
                if p:
                    te = p.select_one(".e_timeFormat-11")
                    if te:
                        date = te.get_text(strip=True)
                        break

        items.append({"title": title, "url": href, "date": date})
    return items


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

    title = ""
    h1 = soup.select_one("h1")
    if h1:
        title = h1.get_text(strip=True)

    # Date: find any date pattern in e_timeFormat or similar
    date_text = ""
    for c in ["e_timeFormat-11", "e_timeFormat-6", "p_show", "p_create"]:
        el = soup.select_one(f".{c}")
        if el:
            txt = el.get_text(strip=True)
            m = re.search(r"(\d{4}-\d{2}-\d{2})", txt)
            if m:
                date_text = m.group(1)
                break

    content = ""
    attachments = []

    content_div = soup.select_one(".e_richText-8, .richText")
    if not content_div:
        # Fallback: look for any div with substantial text
        for c in ["[class*=content]", "[class*=detail]", "[class*=article]"]:
            el = soup.select_one(c)
            if el and el.get_text(" ", strip=True) and len(el.get_text(" ", strip=True)) > 50:
                content_div = el
                break

    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():
                continue
            if src.startswith("//"):
                src = "http:" + src
            elif src.startswith("/"):
                src = BASE_URL + src
            elif not src.startswith("http"):
                src = url.rsplit("/", 1)[0] + "/" + src
            alt = el.get("alt", "") or ""
            parts.append(f"![{alt}]({src})")
            continue

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

        # <p> text
        text = el.get_text(" ", strip=True)
        if text:
            for a in el.find_all("a", href=True):
                ah = a["href"]
                if re.search(r'\.(docx?|pdf|xlsx?|rar|zip)$', ah, re.I):
                    atitle = a.get_text(strip=True) or "附件"
                    if ah.startswith("/"):
                        ah = BASE_URL + ah
                    elif not ah.startswith("http"):
                        ah = url.rsplit("/", 1)[0] + "/" + ah
                    attachments.append({"title": atitle, "url": ah})
            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, timeout=60)
    c = conn.cursor()

    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 = []
    total_pages = 4  # 26 items / 8 per page = ~4 pages
    if _MAX_PG:
        total_pages = min(total_pages, _MAX_PG)

    for pg in range(total_pages):
        offset = pg * PAGE_SIZE
        url = f"{BASE_URL}{LIST_URL.format(offset=offset)}"
        html = fetch(url)
        if not html:
            break
        items = extract_items(html)
        if not items:
            break
        # Deduplicate by URL
        seen_urls = set()
        unique_items = []
        for item in items:
            if item["url"] not in seen_urls:
                seen_urls.add(item["url"])
                unique_items.append(item)
        print(f"[INFO] Page {pg+1} (offset={offset}): {len(unique_items)} unique items", flush=True)
        all_items.extend(unique_items)

    print(f"[INFO] Total items from list: {len(all_items)}", flush=True)

    new_count = 0
    skip_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["url"],))
        if c.fetchone():
            skip_count += 1
            continue

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

        html = fetch(item["url"])
        if not html:
            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_list = detail["attachments"]

        if not content.strip():
            empty_count += 1
            if idx % 3 == 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_list, ensure_ascii=False) if attachments_list 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["url"], date_text, content, summary, att_json, date_rank)
            )
            if c.rowcount > 0:
                new_count += 1
                total_att += len(attachments_list)
        except Exception as e:
            if idx % 3 == 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, {skip_count} skip, {empty_count} empty, {total_att} attachments", flush=True)


if __name__ == "__main__":
    main()
