#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
天长市人民政府 - 基层政务公开【生态环境】>行政审批 栏目爬虫
列表: /public/column/161056932?type=4&catId=170139169&action=list (静态 HTML, ul.xxgk_navli2 > li > a.title)
详情: /public/161056932/{id}.html, meta ArticleTitle/PubDate/ContentSource + div.gkwz_contnet.j-fontContent
"""

import re, sys, json, time, requests, sqlite3
from bs4 import BeautifulSoup
from urllib.parse import urljoin

BASE_URL = "https://www.tianchang.gov.cn"
LIST_URL = BASE_URL + "/public/column/161056932?type=4&catId=170139169&action=list"
DB_PATH = "/root/search.db"
SITE_NAME = "天长市-生态环境行政审批"
CATEGORY = GROUP = "安徽滁州"

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",
    "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8",
    "Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8",
}


def init_db():
    conn = sqlite3.connect(DB_PATH, timeout=60)
    conn.execute("PRAGMA journal_mode=WAL")
    conn.execute("PRAGMA busy_timeout=5000")
    return conn


def get_soup(url):
    try:
        r = requests.get(url, headers=HEADERS, timeout=30)
        r.encoding = "utf-8"
        if r.status_code != 200:
            return None
        return BeautifulSoup(r.text, "html.parser")
    except:
        return None


def extract_list_items(soup):
    """a.title (href 完整URL, title 属性完整标题) + 相邻 span.date"""
    items = []
    for a in soup.find_all("a", class_="title"):
        if not a.get("href"):
            continue
        title = (a.get("title") or a.get_text(strip=True) or "").strip()
        if not title:
            continue
        href = a["href"].strip()
        full = href if href.startswith("http") else urljoin(BASE_URL, href)
        # 日期: li > span.date
        date = ""
        li = a.find_parent("li")
        if li:
            span = li.find("span", class_="date")
            date = span.get_text(strip=True) if span else ""
        items.append({"title": title, "url": full, "date": date})
    return items


def extract_detail(url):
    try:
        r = requests.get(url, headers=HEADERS, timeout=30)
        r.encoding = "utf-8"
        if r.status_code != 200:
            return None, None, None, None, None, None
    except Exception as e:
        print("  [ERROR] fetch: %s" % e, file=sys.stderr)
        return None, None, None, None, None, None

    soup = BeautifulSoup(r.text, "html.parser")

    title = ""
    m = soup.find("meta", attrs={"name": "ArticleTitle"})
    if m and m.get("content"):
        title = m["content"].strip()
    if not title:
        h1 = soup.find("h1")
        if h1:
            title = h1.get_text(strip=True)

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

    src_url = ""
    m = soup.find("meta", attrs={"name": "ContentSource"})
    if m and m.get("content"):
        src_url = m["content"].strip()

    div = soup.find("div", class_="j-fontContent") or \
          soup.find("div", class_="gkwz_contnet") or \
          soup.find("div", class_="wzcon") or \
          soup.find("div", class_="ls-content-con") or \
          soup.find("div", class_="ls-content")
    parts = []
    attach = []

    if div:
        for noise in div.find_all(["script", "style"]):
            noise.decompose()

        for child in div.find_all(["p", "table", "img", "a"], recursive=True):
            if child.name == "table":
                rows = child.find_all("tr")
                md = []
                for ri, row in enumerate(rows):
                    cells = row.find_all(["td", "th"])
                    ct = [c.get_text(" ", strip=True) for c in cells]
                    if not ct:
                        continue
                    md.append("| " + " | ".join(ct) + " |")
                    if ri == 0 and len(ct) > 1:
                        md.append("| " + " | ".join(["---"] * len(ct)) + " |")
                if md:
                    parts.append("\n".join(md))
            elif child.name == "p":
                txt = child.get_text(" ", strip=True)
                if txt and len(txt) > 2:
                    parts.append(txt)
            elif child.name == "img":
                src = child.get("src", "")
                alt = child.get("alt", "")
                if src:
                    if not src.startswith("http"):
                        src = urljoin(url, src)
                    parts.append("![%s](%s)" % (alt or "", src))
            elif child.name == "a":
                h = child["href"].strip()
                if re.search(r"\.(pdf|doc|docx|xls|xlsx|zip|rar)$", h, re.I):
                    fh = h if h.startswith("http") else urljoin(url, h)
                    attach.append({"name": child.get_text(strip=True) or h.split("/")[-1], "url": fh})

    content = "\n\n".join(parts)
    if len(content.strip()) < 20:
        content = '<p><a href="%s">%s</a></p>' % (url, title or url.split('/')[-1])
    summary = content[:200] if len(content) > 200 else content
    return title, pub_date, src_url, content, summary, json.dumps(attach, ensure_ascii=False) if attach else ""


def main():
    import argparse
    parser = argparse.ArgumentParser()
    parser.add_argument("--max-pages", type=int, default=1)
    parser.add_argument("--full", action="store_true")
    args = parser.parse_args()
    max_pages = 1  # 该栏目固定单页 13 条

    all_items, seen = [], set()
    print("列表页: %s" % LIST_URL)
    soup = get_soup(LIST_URL)
    if not soup:
        print("  FAILED")
        return
    items = extract_list_items(soup)
    print("  本页%d条" % len(items))
    for it in items:
        if it["url"] not in seen:
            seen.add(it["url"])
            all_items.append(it)

    print("\n共%d篇文章，开始抓取详情..." % len(all_items))
    conn = init_db()
    ins, err = 0, 0
    SQL = "INSERT OR REPLACE INTO gov_raw (site_name, source_url, page_url, title, publish_date, summary, content, category, attachments, group_name) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"

    for idx, it in enumerate(all_items):
        try:
            print("  [%d/%d] %s..." % (idx + 1, len(all_items), it["title"][:40]))
            t, d, s, c, sm, a = extract_detail(it["url"])
            if t is None:
                err += 1
                continue
            conn.execute(SQL, (SITE_NAME, s or it["url"], it["url"], (t or it["title"]).strip(), d or it["date"],
                               sm or c[:200] if c else it["title"], c, CATEGORY, a, GROUP))
            conn.commit()
            ins += 1
            time.sleep(0.3)
        except Exception as e:
            print("  ERROR: %s" % e)
            err += 1
    conn.close()
    print("\n完成！新增%d条，错误%d条" % (ins, err))


if __name__ == "__main__":
    main()
