#!/usr/bin/env python3
"""新化化工-新闻公告爬虫
https://www.xhchem.com/news/typeid/2.html
企业网站, 16条/页, /page/N.html分页
列表: div.n2 > ul > li (n2_1日期, n2_2 > h4 > a标题)
详情: title标签, div.xinwen_con正文(PDF为主)
"""
import requests
import sqlite3
import json
import os
import re
import argparse
from urllib.parse import urljoin
from bs4 import BeautifulSoup

BASE_URL = "https://www.xhchem.com"
LIST_URL = "https://www.xhchem.com/news/typeid/2.html"

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.n2 > ul > li > div.n2_1(日期) + div.n2_2 > h4 > a"""
    items = []
    n2 = soup.find("div", class_="n2")
    if not n2:
        return items
    ul = n2.find("ul")
    if not ul:
        return items
    for li in ul.find_all("li"):
        a = li.find("a")
        if not a:
            continue
        href = a.get("href", "")
        if not href or href.startswith("#") or href.startswith("javascript"):
            continue
        full_url = urljoin(LIST_URL, href)
        title = a.get("title", "") or a.get_text(strip=True)

        # Date from div.n2_1: h7=day, text=year-month
        pub_date = ""
        date_div = li.find("div", class_="n2_1")
        if date_div:
            day_el = date_div.find("h7")
            day = day_el.get_text(strip=True).zfill(2) if day_el else ""
            ym = date_div.get_text(strip=True).replace(day, "", 1).strip() if day else ""
            if day and ym:
                pub_date = ym + "-" + day

        items.append((full_url, title, pub_date))
    return items


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

    # Title - <title> tag
    title_tag = soup.find("title")
    if title_tag:
        title = title_tag.get_text(strip=True)

    # Content - div.xinwen_con
    article = soup.select_one("div.xinwen_con")
    if not article:
        article = soup.select_one("div.divBox")

    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
        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)

        # PDF/attachment only fallback
        if len(content.strip()) < 20 and attachments:
            att_links = "\n".join("- [%s](%s)" % (a["name"], a["url"]) for a in attachments)
            content = '<p><a href="%s">%s</a></p>\n\n附件：\n%s' % (url, title, att_links) if title else att_links

    return title, pub_date, source, content, attachments


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

    # Build page list
    pages = [LIST_URL]
    if max_pages is None or max_pages > 1:
        limit = max_pages if max_pages else 99
        for n in range(2, limit + 1):
            pages.append("https://www.xhchem.com/news/typeid/2/page/%d.html" % n)

    all_items = []
    for page_url in pages:
        try:
            soup = get_soup(page_url)
            items = parse_list_page(soup)
            if not items:
                print("[列表] %s -> 0 条" % page_url)
                break
            print("[列表] %s -> %d 条" % (page_url, len(items)))
            all_items.extend(items)
        except Exception as e:
            print("[列表] %s -> 异常: %s" % (page_url, str(e)))
            break

    print("\n列表共 %d 条，开始抓详情..." % 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("  [%d/%d] 跳过: %s..." % (idx, len(all_items), list_title[:30]))
            continue

        print("  [%d/%d] %s..." % (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("    -> 新增 (%d chars, %d attachments)" % (len(content), len(attachments)))
        except Exception as e:
            error_count += 1
            print("    -> 异常: %s" % str(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("\n完成: 新增 %d, 跳过 %d, 列表 %d, 异常 %d" % (new, skip, total, errors))
