#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
crawl_njghes_tzgg.py - 南京国环科技-公示通知
CMS: 自定义PHP + Vue.js
列表: /html/web/news/gongshitongzhi/index.html  → list-{N}.html (4页)
      ul > li > a + h3(标题) + div.date-year(月-日+年)
详情: /html/web/news/gongshitongzhi/{id}.html
标题: <title>标签 (取" - "之前)
日期: 正文中 "时间：YYYY-MM-DD"
内容: 正文文本 (去头去尾)
"""
import requests
import re
import sys
import os
import time
from bs4 import BeautifulSoup

DB_PATH = "/root/search.db"
BASE_URL = "https://www.njghes.com"
SITE_NAME = "南京国环-公示通知"
GROUP = "企业"
INDUSTRY = "环境公示"

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",
}

SESSION = None


def get(url):
    global SESSION
    if SESSION is None:
        SESSION = requests.Session()
        SESSION.headers.update(HEADERS)
    try:
        r = SESSION.get(url, timeout=30, verify=False)
        r.encoding = "utf-8"
        return r.text
    except Exception as e:
        print(f"ERR:{e}")
        return None


def fetch_list_page(page_no):
    if page_no == 1:
        url = BASE_URL + "/html/web/news/gongshitongzhi/index.html"
    else:
        url = BASE_URL + f"/html/web/news/gongshitongzhi/list-{page_no}.html"
    return get(url)


def parse_list(html):
    """Extract (url, title, date) from list page"""
    items = []
    soup = BeautifulSoup(html, "html.parser")
    # Find the news list
    news_con = soup.find("div", class_="news_con")
    if not news_con:
        return items
    ul = news_con.find("ul")
    if not ul:
        return items

    for li in ul.find_all("li", recursive=False):
        a = li.find("a")
        h3 = li.find("h3")
        if not a or not a.get("href"):
            continue
        href = a.get("href", "").strip()
        title = h3.get_text(strip=True) if h3 else ""
        if not title:
            title = a.get("title", "") or a.get_text(strip=True)

        # Date from div.date-year
        date_str = ""
        date_year = li.find("div", class_="date-year")
        if date_year:
            date_div = date_year.find("div", class_="date")
            year_div = date_year.find("div", class_="year")
            if date_div and year_div:
                mmdd = date_div.get_text(strip=True)
                yyyy = year_div.get_text(strip=True)
                if mmdd and yyyy:
                    date_str = f"{yyyy}-{mmdd}"

        if href.startswith("/"):
            href = BASE_URL + href
        items.append((href, title, date_str))
    return items


def extract_detail(html, url):
    soup = BeautifulSoup(html, "html.parser")

    # Title from <title> tag
    title = ""
    title_tag = soup.find("title")
    if title_tag:
        raw = title_tag.get_text(strip=True)
        # Remove site name suffix if present
        parts = raw.split(" - ")
        title = parts[0].strip() if parts else raw

    # Date: search for "时间：YYYY-MM-DD" in visible text
    date_str = ""
    body = soup.find("body")
    if body:
        m = re.search(r"时间：(\d{4}-\d{2}-\d{2})", body.get_text())
        if m:
            date_str = m.group(1)

    # Content: from div.con_id (preserves <p> paragraph structure)
    content = ""
    con_id = soup.find("div", class_="con_id")
    if con_id:
        paragraphs = []
        for p in con_id.find_all("p"):
            txt = p.get_text(strip=True)
            if txt:
                paragraphs.append(txt)
        if paragraphs:
            content = "\n\n".join(paragraphs)
        else:
            # Fallback: get all text from con_id
            content = con_id.get_text(separator="\n").strip()

    # Clean up content
    if content:
        content = re.sub(r"&nbsp;", "", content)

    summary = content[:200] if content else ""
    return title, date_str, content, summary


def save_to_db(items_data):
    import sqlite3
    conn = sqlite3.connect(DB_PATH, timeout=10)
    c = conn.cursor()
    inserted = 0
    fts_batch = []
    for title, date_str, content, summary, page_url in items_data:
        try:
            c.execute("SELECT id FROM gov_raw WHERE page_url = ?", (page_url,))
            if c.fetchone():
                continue
            c.execute(
                """INSERT INTO gov_raw 
                   (page_url, title, site_name, publish_date, content, summary,
                    source_url, category, industry, group_name, script_name)
                   VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)""",
                (page_url, title, SITE_NAME, date_str, content, summary,
                 page_url, "环境公示", INDUSTRY, GROUP, "crawl_njghes_tzgg.py"),
            )
            new_id = c.lastrowid
            if new_id:
                fts_batch.append((new_id, title, SITE_NAME, summary or ""))
            inserted += 1
        except Exception as e:
            print(f"  [DB ERROR] {title[:30]}: {e}")
    conn.commit()
    if fts_batch:
        for rid, title, site, summary in fts_batch:
            try:
                c.execute(
                    "INSERT OR IGNORE INTO gov_search(rowid, title, site_name, summary) VALUES (?, ?, ?, ?)",
                    (rid, title, site, summary),
                )
            except Exception as e:
                print(f"  [FTS ERROR] id={rid}: {e}")
        conn.commit()
        print(f"  FTS同步: {len(fts_batch)}条")
    conn.close()
    return inserted


def main():
    import argparse
    parser = argparse.ArgumentParser(description=f"{SITE_NAME}爬虫")
    parser.add_argument("--pages", type=int, default=1, help="爬取页数(共4页)")
    parser.add_argument("--full", action="store_true", help="全量爬取")
    args = parser.parse_args()

    max_pages = 4 if args.full else args.pages
    total_new = 0

    for page_no in range(1, max_pages + 1):
        print(f"[{time.strftime('%H:%M:%S')}] 第{page_no}页...", end=" ", flush=True)
        html = fetch_list_page(page_no)
        if not html:
            print("失败，停止")
            break

        items = parse_list(html)
        if not items:
            print("无数据，停止")
            break
        print(f"{len(items)}条", flush=True)

        batch = []
        for href, title, date_str in items:
            detail_html = get(href)
            if not detail_html:
                continue
            dt, dd, content, summary = extract_detail(detail_html, href)
            batch.append((dt or title, dd or date_str, content, summary, href))
            time.sleep(0.3)

        saved = save_to_db(batch)
        total_new += saved
        print(f"  入库{saved}/{len(batch)}条 (累计{total_new})", flush=True)
        if not args.full and saved == 0 and len(batch) > 0:
            print("  全部已存在，增量停止")
            break

    print(f"\n===== 完成 =====")
    print(f"新增入库: {total_new} 条")
    print(f"站点: {SITE_NAME}")


if __name__ == "__main__":
    main()
