#!/usr/bin/env python3
"""遵义市播州区-通知公告 爬虫"""
import re
import json
import time
import hashlib
import requests
from datetime import datetime
from bs4 import BeautifulSoup

BASE_URL = "https://www.zybz.gov.cn"
LIST_URL = f"{BASE_URL}/xwzx/tzgg"
SITE_NAME = "遵义市播州区-通知公告"
TOTAL_PAGES = 9  # createPageHTML(9, 0, ...)

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

session = requests.Session()
session.headers.update(HEADERS)


def get_list_url(page):
    if page <= 1:
        return f"{LIST_URL}/index.html"
    return f"{LIST_URL}/index_{page}.html"


def parse_list_page(html):
    """Parse list page, return list of (url, title, date_str)"""
    items = []
    # <ul class="Con_list"> -> <li> -> <a TARGET="_blank" href="..." title="FULL TITLE">...</a> <span>YYYY-MM-DD</span>
    ulm = re.search(r'<ul[^>]*class="Con_list"[^>]*>(.*?)</ul>', html, re.DOTALL)
    if not ulm:
        return items
    
    uls = ulm.group(1)
    li_pattern = re.compile(r'<li[^>]*>(.*?)</li>', re.DOTALL)
    for m in li_pattern.finditer(uls):
        li = m.group(1)
        a_m = re.search(r'<a[^>]*href="([^"]+)"[^>]*title="([^"]*)"', li)
        if not a_m:
            continue
        href = a_m.group(1).strip()
        title = a_m.group(2).strip()
        # Date from <span>YYYY-MM-DD</span>
        date_m = re.search(r'<span>(\d{4}-\d{2}-\d{2})</span>', li)
        date_str = date_m.group(1).strip() if date_m else ""
        items.append((href, title, date_str))
    return items


def parse_detail(html, url):
    """Parse detail page"""
    soup = BeautifulSoup(html, "html.parser")

    # Title from <title>
    title_tag = soup.find("title")
    full_title = title_tag.get_text(strip=True) if title_tag else ""
    full_title = re.sub(r"[-—]+\s*通知公告.*?播州区.*?$", "", full_title).strip()

    # Content - TRS_UEDITOR or content div
    content_div = soup.find("div", class_="trs_editor_view")
    if not content_div:
        content_div = soup.find("div", class_="TRS_UEDITOR")
    if not content_div:
        content_div = soup.find("div", class_="content")
    if not content_div:
        all_divs = soup.find_all("div")
        for d in all_divs:
            classes = d.get("class", [])
            text = d.get_text(strip=True)
            if len(text) > 300 and any(c in str(classes) for c in ["content", "article", "main"]):
                content_div = d
                break

    content_html = ""
    attachments = []

    if content_div:
        # Attachments from all page links
        for a_tag in soup.find_all("a"):
            href = a_tag.get("href", "")
            a_text = a_tag.get_text(strip=True)
            if re.search(r"\.(doc|docx|pdf|xls|xlsx|zip|rar)$", href, re.I):
                if not href.startswith("http"):
                    if href.startswith("//"):
                        href = f"https:{href}"
                    elif href.startswith("/"):
                        href = f"{BASE_URL}{href}"
                    elif href.startswith("./"):
                        href = f"{BASE_URL}/xwzx/tzgg/{href[2:]}"
                    else:
                        href = f"{BASE_URL}/{href}"
                if len(a_text) > 2:
                    attachments.append({"title": a_text, "url": href})
                    a_tag.replace_with(f"[{a_text}]({href})")

        # Handle tables
        for table in content_div.find_all("table"):
            table_html = str(table)
            table.replace_with(f"\n\n[TABLE]\n{table_html}\n[/TABLE]\n")

        # Get paragraphs
        content_parts = []
        for child in content_div.children:
            tag_name = getattr(child, "name", None)
            if tag_name == "p":
                text = child.get_text(" ", strip=True).strip()
                if text:
                    content_parts.append(text)
            elif tag_name == "div":
                text = child.get_text(" ", strip=True).strip()
                if text:
                    content_parts.append(text)
            elif child.name is None:
                text = str(child).strip()
                if text:
                    content_parts.append(text)

        if not content_parts:
            content_html = content_div.get_text(" ", strip=True)
        else:
            content_html = "\n\n".join(content_parts)

        content_html = re.sub(
            r"\[TABLE\]\n(.*?)\n\[/TABLE\]",
            lambda m: f"\n\n{m.group(1)}\n\n",
            content_html, flags=re.DOTALL,
        )

        # Filter metadata
        metadata_patterns = [
            r"^责任编辑[：:]", r"^初审[：:]", r"^复审[：:]", r"^终审[：:]",
            r"^\[纠错\]", r"^【纠错】", r"^扫一扫在手机打开当前页",
        ]
        lines = content_html.split("\n")
        filtered_lines = []
        for line in lines:
            stripped = line.strip()
            skip = False
            for pat in metadata_patterns:
                if re.match(pat, stripped):
                    skip = True
                    break
            if not skip:
                filtered_lines.append(line)
        content_html = "\n".join(filtered_lines).strip()

        # PDF empty content fallback
        if len(content_html.strip()) < 20:
            content_html = f'<p><a href="{url}">{full_title}</a></p>\nPDF附件见原文链接'
            if attachments:
                for att in attachments:
                    content_html += f"\n📎 {att['title']}: {att['url']}"

    # Publish date
    pub_date = ""
    meta_date = soup.find("meta", attrs={"name": "PubDate"})
    if meta_date and meta_date.get("content"):
        pub_date = meta_date["content"].strip()[:10]
    if not pub_date:
        date_matches = re.findall(r"(\d{4}-\d{1,2}-\d{1,2})", html)
        if date_matches:
            pub_date = date_matches[0]

    return {
        "title": full_title,
        "content": content_html,
        "publish_date": pub_date,
        "attachments": json.dumps(attachments, ensure_ascii=False),
        "source_url": url,
    }


def crawl_pages(max_pages, page_start=1, page_end=None):
    if page_end is None:
        page_end = max_pages

    results = []
    total_listed = 0

    for page in range(page_start, page_end + 1):
        url = get_list_url(page)
        print(f"[列表] 第{page}页: {url}", flush=True)

        try:
            resp = session.get(url, timeout=30)
            resp.encoding = "utf-8"
            if resp.status_code != 200:
                print(f"  -> HTTP {resp.status_code}, 跳过", flush=True)
                continue
        except Exception as e:
            print(f"  -> 请求失败: {e}", flush=True)
            time.sleep(2)
            continue

        items = parse_list_page(resp.text)
        print(f"  -> 解析到 {len(items)} 条", flush=True)
        total_listed += len(items)

        if not items:
            break

        for idx, (item_url, list_title, date_str) in enumerate(items, 1):
            print(f"  [{idx}/{len(items)}] {list_title[:60]}...", flush=True)
            try:
                dresp = session.get(item_url, timeout=30)
                dresp.encoding = "utf-8"
                if dresp.status_code != 200:
                    print(f"    -> HTTP {dresp.status_code}", flush=True)
                    continue
            except Exception as e:
                print(f"    -> 详情页请求失败: {e}", flush=True)
                time.sleep(1)
                continue

            detail = parse_detail(dresp.text, item_url)
            if detail["title"]:
                list_title = detail["title"]
            detail["list_title"] = list_title
            detail["list_date"] = date_str
            results.append(detail)
            time.sleep(0.3)

        time.sleep(1)

    print(f"\n总计: 列表 {total_listed} 条, 详情 {len(results)} 条", flush=True)
    return results


def output_jsonl(results, output_path):
    count = 0
    with open(output_path, "w", encoding="utf-8") as f:
        for r in results:
            item_id = hashlib.md5(r["source_url"].encode()).hexdigest()
            record = {
                "id": item_id,
                "title": r["title"] or r["list_title"],
                "site_name": SITE_NAME,
                "source_url": r["source_url"],
                "publish_date": r["publish_date"] or r["list_date"],
                "content": r["content"],
                "attachments": r["attachments"],
                "created_at": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
                "updated_at": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
            }
            f.write(json.dumps(record, ensure_ascii=False) + "\n")
            count += 1
    print(f"输出 {count} 条到 {output_path}", flush=True)
    return count


if __name__ == "__main__":
    import argparse

    parser = argparse.ArgumentParser(description="遵义市播州区-通知公告 爬虫")
    parser.add_argument("--pages", type=int, default=TOTAL_PAGES)
    parser.add_argument("--output", default="")
    parser.add_argument("--page-start", type=int, default=1)
    parser.add_argument("--page-end", type=int, default=None)
    args = parser.parse_args()

    page_end = args.page_end or args.pages
    results = crawl_pages(args.pages, args.page_start, page_end)

    output_path = args.output or f"/root/gov_crawler/output/zybz_tzgg_{datetime.now().strftime('%Y%m%d_%H%M%S')}.jsonl"
    import os
    os.makedirs(os.path.dirname(output_path) or ".", exist_ok=True)
    count = output_jsonl(results, output_path)
    print(f"DONE: {count}条", flush=True)
