#!/usr/bin/env python3
"""
息烽县-环境监测爬虫
http://www.xifeng.gov.cn/zfxxgk/fdzdgknr/zdmsxx/hjbh_5620299/
实际列表: http://www.xifeng.gov.cn/zwgk/zdlygk/sthj/hjjc_5741522/
共9页，前8页20条/页，第9页9条，总计169条
分页: index.html(第1页), index_2.html ... index_9.html
"""
import requests
import sqlite3
import json
import os
import argparse
import re
from bs4 import BeautifulSoup

BASE_URL = "https://www.xifeng.gov.cn"
LIST_PATH = "/zwgk/zdlygk/sthj/hjjc_5741522"
TOTAL_PAGES = 9

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=20):
    resp = requests.get(url, headers=HEADERS, timeout=timeout)
    resp.encoding = "utf-8"
    return BeautifulSoup(resp.text, "html.parser")


def parse_list_page(soup):
    """提取列表页: div.nr_ej > ul > li > a + span"""
    items = []
    for li in soup.select("div.nr_ej li"):
        a = li.find("a")
        if not a:
            continue
        href = a.get("href", "")
        if "hjjc_5741522" not in href:
            continue
        if not href.startswith("http"):
            href = BASE_URL + href if href.startswith("/") else href
        title = a.get_text(strip=True)
        span = li.find("span")
        pub_date = span.get_text(strip=True) if span else ""
        items.append((href, title, pub_date))
    return items


def extract_detail(soup, url):
    """提取详情页"""
    title = ""
    pub_date = ""
    source = ""
    content = ""
    attachments = []

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

    # PubDate - meta
    meta_pd = soup.find("meta", attrs={"name": "PubDate"})
    if meta_pd and meta_pd.get("content"):
        pub_date = meta_pd["content"].strip()

    # Source - meta
    meta_src = soup.find("meta", attrs={"name": "ContentSource"})
    if meta_src and meta_src.get("content"):
        source = meta_src["content"].strip()

    # Content - div.trs_editor_view
    article = soup.select_one("div.trs_editor_view")
    if article:
        # 提取附件
        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 = BASE_URL + a_href
                attachments.append({
                    "name": a_tag.get_text(strip=True) or os.path.basename(a_href),
                    "url": a_href,
                })

        # 提取正文，保留 table 原始 HTML
        text_parts = []
        for child in article.children:
            if not hasattr(child, "name") or not child.name:
                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)

        content = "\n".join(text_parts)

        # fallback
        if len(content.strip()) < 50:
            content = article.get_text(strip=True, separator="\n")

    return title, pub_date, source, content, attachments


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

    all_items = []
    pages_to_crawl = TOTAL_PAGES
    if max_pages and max_pages < pages_to_crawl:
        pages_to_crawl = max_pages

    for page in range(1, pages_to_crawl + 1):
        if page == 1:
            url = f"{BASE_URL}{LIST_PATH}/"
        else:
            url = f"{BASE_URL}{LIST_PATH}/index_{page}.html"

        print(f"[列表] 第{page}/{pages_to_crawl}页: {url}")
        try:
            soup = get_soup(url)
            items = parse_list_page(soup)
            if not items:
                print("  -> 空页，停止")
                break
            print(f"  -> {len(items)} 条")
            all_items.extend(items)
        except Exception as e:
            print(f"  -> 失败: {e}")
            break

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

    new_count = 0
    error_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():
            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)
                VALUES (?, ?, ?, ?, ?, ?, ?)""",
                (page_url, SITE_NAME, title, pub_date, page_url, content, att_json),
            )
            conn.commit()
            new_count += 1
            print(f"    -> 新增")
        except Exception as e:
            error_count += 1
            print(f"    -> 异常: {e}")

    conn.close()
    return new_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, total, errors = crawl(args.max_pages)
    print(f"\n完成: 新增 {new}, 列表 {total}, 异常 {errors}")
