#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Crawler for 泉州市泉港区人民政府 - 项目环评 (qg.gov.cn)
CMS: TRS (填选系统)
List: div.gl_list > ul > li > span(date) + a[href]
Pagination: index_0.htm ~ index_29.htm (15/page, 30 pages ~450 items)
Detail: div.xl_tit (title), div.xl_tit1_l > span:nth(1) (date), div.TRS_Editor (content)
         div.szf_list2 ul li a (attachments)

Usage:
    python3 /root/gov_crawler/crawl_qg_xmhp.py
"""

import requests, re, json, sqlite3, time, os, sys
from datetime import datetime
from bs4 import BeautifulSoup
from urllib.parse import urljoin

DB_PATH = "/root/search.db"
SITE_NAME = "泉港区-项目环评"
CATEGORY = "项目环评"
GROUP = "福建"
BASE_URL = "http://www.qg.gov.cn"
LIST_DIR = "/zwgk/zdxxgk/hjbh/xmhp"
TOTAL_PAGES = 30

HEADERS = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36",
    "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
    "Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8",
}


# ---------- List ----------

def get_list_url(page_num):
    """page_num is 1-indexed"""
    if page_num == 1:
        return f"{BASE_URL}{LIST_DIR}/"
    return f"{BASE_URL}{LIST_DIR}/index_{page_num-1}.htm"


def extract_list_page(page_num):
    url = get_list_url(page_num)
    try:
        r = requests.get(url, headers=HEADERS, timeout=20)
        r.encoding = "utf-8"
        soup = BeautifulSoup(r.text, "html.parser")
    except Exception as e:
        print(f"  Error fetching {url}: {e}", file=sys.stderr)
        return []

    div = soup.find("div", class_="gl_list")
    if not div:
        print(f"  No gl_list found on page {page_num}", file=sys.stderr)
        return []

    items = []
    for ul in div.find_all("ul"):
        for li in ul.find_all("li"):
            a = li.find("a")
            span = li.find("span")
            if not a or not a.get("href"):
                continue

            href = a["href"].strip()
            page_url = urljoin(url, href)
            title = a.get("title", "").strip() or a.get_text(strip=True)
            date_str = span.get_text(strip=True) if span else ""

            if title and page_url:
                items.append((title, page_url, date_str))

    return items


# ---------- Detail ----------

def fetch_detail(url):
    try:
        r = requests.get(url, headers=HEADERS, timeout=20)
        r.encoding = "utf-8"
    except Exception as e:
        print(f"  fetch_detail error {url}: {e}", file=sys.stderr)
        return None, None, None, []

    soup = BeautifulSoup(r.text, "html.parser")

    # --- Title ---
    title = ""
    tit_div = soup.find("div", class_="xl_tit")
    if tit_div:
        title = tit_div.get_text(strip=True)
    if not title:
        t = soup.find("title")
        if t:
            title = t.get_text(strip=True).split("-")[0].strip()

    # --- Date ---
    date_str = ""
    # From meta tag
    meta = soup.find("meta", attrs={"name": "PubDate"})
    if meta and meta.get("content"):
        date_str = meta["content"].strip()[:10]
    if not date_str:
        # From div.xl_tit1_l spans
        tit1 = soup.find("div", class_="xl_tit1_l")
        if tit1:
            spans = tit1.find_all("span")
            for sp in spans:
                txt = sp.get_text(strip=True)
                m = re.search(r"(\d{4}-\d{2}-\d{2})", txt)
                if m:
                    date_str = m.group(1)
                    break

    # --- Content ---
    editor = soup.find("div", class_="TRS_Editor")
    if not editor:
        # Fallback
        editor = soup.find("div", class_="xl_con1")
    content = ""
    if editor:
        for s in editor.find_all(["script", "style"]):
            s.decompose()
        parts = []
        # Iterate direct children (p, table, div)
        for child in editor.children:
            if not child.name:
                continue
            if child.name == "table":
                parts.append(str(child))
            elif child.name == "p":
                # Skip container p wrapping div
                if child.find(["div", "table"], recursive=False):
                    for inner in child.find_all(["p", "table"], recursive=True):
                        if inner.name == "table":
                            parts.append(str(inner))
                        elif not inner.find_parent("table"):
                            t = inner.get_text(strip=True)
                            if t:
                                parts.append(t)
                else:
                    t = child.get_text(strip=True)
                    if t:
                        parts.append(t)
            elif child.name == "div":
                txt = child.get_text(strip=True)
                if txt:
                    parts.append(txt)
        content = "\n\n".join(parts)

    # Remove pure-whitespace paragraphs
    content = re.sub(r"\n{3,}", "\n\n", content).strip()

    # --- Attachments ---
    attachments = []
    seen = set()
    # Primary attachment area
    att_div = soup.find("div", class_="szf_list2")
    if att_div:
        for a_tag in att_div.find_all("a", href=True):
            href = a_tag["href"]
            full_url = urljoin(url, href)
            name = a_tag.get_text(strip=True) or href.split("/")[-1].split("?")[0]
            if full_url not in seen:
                seen.add(full_url)
                attachments.append({"name": name, "url": full_url})
                if content:
                    content += f'\n\n附件：<p><a href="{full_url}">{name}</a></p>'

    # Also check for attachments in TRS_Editor
    for a_tag in editor.find_all("a", href=True) if editor else []:
        href = a_tag["href"]
        if re.search(r"\.(pdf|doc|docx|xls|xlsx|rar|zip|txt)$", href, re.I):
            full_url = urljoin(url, href)
            name = a_tag.get_text(strip=True) or href.split("/")[-1].split("?")[0]
            if full_url not in seen:
                seen.add(full_url)
                attachments.append({"name": name, "url": full_url})

    return title, date_str, content, attachments


# ---------- DB ----------

def with_retry(fn, desc="DB op", max_attempts=10, delay=5):
    for attempt in range(1, max_attempts + 1):
        try:
            return fn()
        except sqlite3.OperationalError as e:
            if "locked" in str(e) and attempt < max_attempts:
                print(f"  {desc}: locked (attempt {attempt}/{max_attempts}), retry in {delay}s...", file=sys.stderr)
                time.sleep(delay)
            else:
                print(f"  {desc} failed: {e}", file=sys.stderr)
                return False
    return False


def init_db():
    conn = sqlite3.connect(DB_PATH, timeout=30)
    conn.execute("PRAGMA journal_mode=WAL")
    conn.execute("PRAGMA busy_timeout=30000")
    return conn


def save_article(conn, title, page_url, publish_date, content, attachments):
    summary = content[:200] if content else title
    summary = re.sub(r"\s+", " ", summary).strip()
    att_json = json.dumps(attachments, ensure_ascii=False) if attachments else "[]"
    try:
        cur = conn.execute(
            """INSERT OR IGNORE INTO gov_raw
               (site_name, source_url, page_url, title, publish_date, summary, content, category, attachments, group_name)
               VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)""",
            (SITE_NAME, page_url, page_url, title.strip(), publish_date,
             summary, content, CATEGORY, att_json, GROUP),
        )
        return cur.rowcount > 0
    except Exception as e:
        print(f"  DB error: {e}", file=sys.stderr)
        return False


# ---------- Main ----------

def main():
    max_pages = TOTAL_PAGES
    if len(sys.argv) > 1:
        try:
            max_pages = int(sys.argv[1])
        except:
            pass

    print(f"Scraping {SITE_NAME}, max pages: {max_pages}", file=sys.stderr)
    conn = init_db()
    total_new = 0
    total_found = 0
    start_time = time.time()

    def do_clean():
        conn.execute("DELETE FROM gov_raw WHERE site_name = ?", (SITE_NAME,))
        conn.commit()
    print("  Cleaning old data...", file=sys.stderr)
    with_retry(do_clean, desc=f"Clean {SITE_NAME}")
    print(f"  Cleaned old data for {SITE_NAME}", file=sys.stderr)

    for pn in range(1, max_pages + 1):
        articles = extract_list_page(pn)
        if not articles:
            print(f"  Page {pn}: 0 items (end)", file=sys.stderr)
            break

        total_found += len(articles)
        batch_new = 0

        for title, page_url, date in articles:
            if date and date < "2005-01-01":
                continue

            cur = conn.execute("SELECT id FROM gov_raw WHERE page_url = ?", (page_url,))
            if cur.fetchone():
                continue

            det_title, det_date, det_content, det_atts = fetch_detail(page_url)
            final_title = det_title or title
            final_date = det_date or date
            final_content = det_content or f"[{final_title}]({page_url})"
            final_atts = det_atts or []

            if save_article(conn, final_title, page_url, final_date, final_content, final_atts):
                total_new += 1
                batch_new += 1

            time.sleep(0.3)

        elapsed = int(time.time() - start_time)
        pages_left = max_pages - pn
        eta = int(pages_left / max(1, pn / max(1, elapsed)) / 60) if elapsed > 0 and pn > 0 else 0

        print(f"  Page {pn}/{max_pages}: +{batch_new} new, "
              f"{total_new}/{total_found} total, "
              f"{elapsed//60}:{elapsed%60:02d} elapsed, "
              f"ETA {eta}min", file=sys.stderr)

        if pn % 5 == 0:
            conn.commit()

    conn.commit()
    elapsed = int(time.time() - start_time)
    conn.close()
    print(f"\nDone! Found: {total_found}, New: {total_new}, Time: {elapsed//60}m{elapsed%60:02d}s", file=sys.stderr)


if __name__ == "__main__":
    main()
