#!/usr/bin/env python3
"""西昌市-环评公示爬虫
https://www.xichang.gov.cn/zfxxgk/zfxxgknr/hjbh_15857/hpgs_15863/
单页15条

关键: 该站IPv6不可达, 需强制IPv4
"""
import socket
import requests
import requests.packages.urllib3.util.connection as urllib3_cn
urllib3_cn.allowed_gai_family = lambda: socket.AF_INET

import sqlite3
import json
import os
import re
import argparse
from urllib.parse import urljoin
from bs4 import BeautifulSoup

BASE_URL = "https://www.xichang.gov.cn"
LIST_URL = "https://www.xichang.gov.cn/zfxxgk/zfxxgknr/hjbh_15857/hpgs_15863/"

DB_PATH = os.environ.get("DB_PATH", "/root/search.db")
SITE_NAME = "西昌市-环评公示"
HEADERS = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/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",
}


def get_soup(url, timeout=30):
    resp = requests.get(url, headers=HEADERS, timeout=timeout)
    resp.encoding = "utf-8"
    return BeautifulSoup(resp.text, "html.parser")


def parse_list_page(soup):
    """列表页: div.list-con > a + span"""
    items = []
    lc = soup.find("div", class_="list-con")
    if not lc:
        return items
    for a in lc.find_all("a"):
        href = a.get("href", "")
        if not href or href.startswith("#") or href.startswith("javascript"):
            continue
        full_url = urljoin(LIST_URL, href)
        title = a.get_text(strip=True)
        span = a.find_previous("span")
        if not span:
            span = a.find_next_sibling("span")
        pub_date = span.get_text(strip=True) if span else ""
        items.append((full_url, title, pub_date))
    return items


def extract_detail(soup, url):
    title = ""
    pub_date = ""
    source = ""
    content = ""
    attachments = []

    # Title - div.nrtitle
    title_div = soup.select_one("div.nrtitle")
    if title_div:
        title = title_div.get_text(strip=True)

    # Source/Date - div.ly: "来源：西昌生态环境局时间：2026-07-02 09:22"
    ly_div = soup.select_one("div.ly")
    if ly_div:
        ly_text = ly_div.get_text(strip=True)
        m = re.search(r'来源[：:]\s*(.+?)(?:时间[：:]|$)', ly_text)
        if m:
            source = m.group(1).strip()
        m = re.search(r'时间[：:]\s*(\d{4}[-/]\d{1,2}[-/]\d{1,2})', ly_text)
        if m:
            pub_date = m.group(1)

    # Content - div.trs_editor_view > div.TRS_UEDITOR
    article = soup.select_one("div.trs_editor_view")
    if not article:
        article = soup.select_one("div.TRS_UEDITOR")
    if not article:
        # fallback: div.nrcont (has breadcrumb prefix, but partial content)
        article = soup.select_one("div.nrcont")

    if article:
        # Attachments
        for a_tag in article.find_all("a"):
            a_href = a_tag.get("href", "")
            if a_href.endswith((".pdf", ".doc", ".docx", ".xls", ".xlsx", ".zip", ".rar")):
                if not a_href.startswith("http"):
                    a_href = urljoin(BASE_URL, a_href)
                attachments.append({
                    "name": a_tag.get_text(strip=True) or os.path.basename(a_href),
                    "url": a_href,
                })

        # Build content preserving tables and paragraphs
        text_parts = []
        for child in article.children:
            if not hasattr(child, "name") or not child.name:
                continue
            if child.name in ("script", "style"):
                continue
            if child.name == "table":
                text_parts.append(str(child))
                text_parts.append("")
            elif child.name in ("p", "div"):
                inner_table = child.find("table")
                if inner_table:
                    text_parts.append(str(inner_table))
                    text_parts.append("")
                    continue
                txt = child.get_text(strip=True)
                if txt:
                    text_parts.append(txt)
            elif child.name in ("br",):
                text_parts.append("")

        content = "\n\n".join(text_parts)

    return title, pub_date, source, content, attachments


def crawl(max_pages=None):
    conn = sqlite3.connect(DB_PATH, timeout=60)
    cur = conn.cursor()

    print(f"[列表] 第1页: {LIST_URL}")
    soup = get_soup(LIST_URL)
    all_items = parse_list_page(soup)
    print(f"  -> {len(all_items)} 条")

    print(f"\n列表共 {len(all_items)} 条，开始抓详情...")
    new_count = 0
    error_count = 0
    skip_count = 0

    for idx, (page_url, list_title, list_date) in enumerate(all_items, 1):
        cur.execute(
            "SELECT id FROM gov_raw WHERE page_url=? AND site_name=?",
            (page_url, SITE_NAME),
        )
        if cur.fetchone():
            skip_count += 1
            print(f"  [{idx}/{len(all_items)}] 跳过: {list_title[:30]}...")
            continue

        print(f"  [{idx}/{len(all_items)}] {list_title[:40]}...")
        try:
            soup = get_soup(page_url)
            title, pub_date, source, content, attachments = extract_detail(soup, page_url)
            if not title:
                title = list_title
            if not pub_date:
                pub_date = list_date

            att_json = json.dumps(attachments, ensure_ascii=False) if attachments else ""

            cur.execute(
                """INSERT OR REPLACE INTO gov_raw (page_url, site_name, title, publish_date, source_url, content, attachments, script_name) VALUES (?, ?, ?, ?, ?, ?, ?, 'crawl_xichang.py')""",
                (page_url, SITE_NAME, title, pub_date, page_url, content, att_json),
            )
            conn.commit()
            new_count += 1
            print(f"    -> 新增 ({len(content)} chars)")
        except Exception as e:
            error_count += 1
            print(f"    -> 异常: {e}")

    conn.close()
    return new_count, skip_count, len(all_items), error_count


if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument("--max-pages", type=int, default=None)
    args = parser.parse_args()

    new, skip, total, errors = crawl(args.max_pages)
    print(f"\n完成: 新增 {new}, 跳过 {skip}, 列表 {total}, 异常 {errors}")
