#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
crawl_ahys_tzgg.py - 颍上县-通知公告
CMS: 自定义 (Content/showList)
列表: /Content/showList/1341/page_{N}.html (静态分页, 20条/页, 25页共484条)
详情: /Content/show/{id}.html
标题: <meta ArticleTitle>
日期: <meta PubDate>
正文: div.Con > p
"""

import requests
import re
import sys
import os
import time
from bs4 import BeautifulSoup

DB_PATH = "/root/search.db"
BASE_URL = "https://www.ahys.gov.cn"
SITE_NAME = "颍上县-通知公告"
GROUP = "安徽"
INDUSTRY = "环境公示"
MAX_PAGES = 25

HEADERS = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/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=60)
        r.encoding = "utf-8"
        return r.text
    except Exception as e:
        print(f"ERR:{e}")
        return None


def parse_list(html):
    """Extract items from list page HTML"""
    items = []
    soup = BeautifulSoup(html, "html.parser")
    for a in soup.select("a[href*='/Content/show/']"):
        href = a.get("href", "")
        title = a.get("title", "") or a.get_text(strip=True)
        if href and title:
            full_url = href if href.startswith("http") else BASE_URL + href
            items.append((full_url, title))
    return items


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

    # Title from <meta ArticleTitle>
    title = ""
    meta_title = soup.find("meta", {"name": "ArticleTitle"})
    if meta_title:
        title = meta_title.get("content", "").strip()

    # Date from <meta PubDate>
    date_str = ""
    pubdate_meta = soup.find("meta", {"name": "PubDate"})
    if pubdate_meta:
        content = pubdate_meta.get("content", "")
        m = re.search(r"(\d{4}-\d{2}-\d{2})", content)
        if m:
            date_str = m.group(1)

    # Content from div.Con
    content = ""
    con = soup.find("div", class_="j-fontContent") or soup.find("div", id="zoom")
    if con:
        parts = []
        for p in con.find_all("p"):
            txt = p.get_text(strip=True)
            if txt:
                parts.append(txt)
        for tbl in con.find_all("table"):
            parts.append(str(tbl))
        if parts:
            content = "\n\n".join(parts)
        else:
            content = con.get_text(separator="\n").strip()

    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_ahys_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="爬取页数(共25页)")
    parser.add_argument("--full", action="store_true", help="全量爬取(25页)")
    args = parser.parse_args()

    max_pages = MAX_PAGES if args.full else args.pages
    print(f"[{time.strftime('%H:%M:%S')}] 开始爬取 {SITE_NAME}...", flush=True)

    all_items = []
    for pg in range(1, max_pages + 1):
        list_url = f"{BASE_URL}/Content/showList/1341/page_{pg}.html"
        html = get(list_url)
        if not html:
            print(f"  第{pg}页: 请求失败")
            continue
        items = parse_list(html)
        print(f"  第{pg}页: {len(items)}条", flush=True)
        all_items.extend(items)

    if not all_items:
        print("无数据")
        return

    print(f"\n共获取 {len(all_items)} 条链接")

    batch = []
    for href, title in all_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 "", content, summary, href))
        time.sleep(0.3)

    saved = save_to_db(batch)
    print(f"入库{saved}/{len(batch)}条")

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


if __name__ == "__main__":
    main()
