#!/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.hehechengde.cn"
LIST_URL = f"{BASE_URL}/news/txy/"
MAX_PAGES = 30

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 LIST_URL
    return f"{BASE_URL}/news/txy/index_{page}.html"


def parse_list_page(html, page):
    """Parse list page, return list of (url, title, date_str)"""
    items = []
    # <dl class="page-list"><dt><a href="URL" title="FULL TITLE">...</a></dt>
    # <dd class="desc"><p>summary</p><p class="date">发布于：<em>YYYY-MM-DD HH:MM.</em></p></dd></dl>
    pattern = re.compile(
        r'<dl class="page-list">(.*?)</dl>', re.DOTALL
    )
    for m in pattern.finditer(html):
        block = m.group(1)
        # URL and title from <a> tag
        a_match = re.search(r'<a[^>]*href="([^"]+)"[^>]*title="([^"]*)"', block)
        if not a_match:
            continue
        url = a_match.group(1).strip()
        title = a_match.group(2).strip()
        if not title:
            # Fallback to link text
            text_match = re.search(r'<a[^>]*>(.*?)</a>', block, re.DOTALL)
            if text_match:
                title = re.sub(r'<[^>]+>', '', text_match.group(1)).strip()
        # Date
        date_match = re.search(r'(\d{4}-\d{1,2}-\d{1,2})', block)
        date_str = date_match.group(1) if date_match else ""
        items.append((url, title, date_str))
    return items


def parse_detail(html, url):
    """Parse detail page, return dict with title, content, date, attachments"""
    soup = BeautifulSoup(html, "html.parser")

    # Title from <title> tag - strip site suffix
    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 from main-content div
    content_div = soup.find("div", class_="main-content")
    if not content_div:
        content_div = soup.find("div", class_="page-content")
    if not content_div:
        content_div = soup.find("div", class_="content")
    if not content_div:
        # Fallback: find the largest text div
        all_divs = soup.find_all("div")
        for d in all_divs:
            text = d.get_text(strip=True)
            if len(text) > 200 and "main" in d.get("class", []) or "content" in d.get("class", []):
                content_div = d
                break

    content_html = ""
    attachments = []
    if content_div:
        # Extract attachments before modifying
        for a_tag in content_div.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"{BASE_URL}{href}"
                    else:
                        href = f"{BASE_URL}/{href}"
                # Skip if it's just a navigation link
                if len(a_text) > 2:
                    attachments.append({"title": a_text, "url": href})
                    a_tag.replace_with(f"[{a_text}]({href})")

        # Handle tables - preserve as HTML
        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 with double newline
        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)

        # Restore TABLE markers
        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 template metadata lines
        metadata_patterns = [
            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']}"

    # Extract publish date from page source
    pub_date = ""
    date_pats = re.findall(r"(\d{4}-\d{1,2}-\d{1,2})", html)
    if date_pats:
        pub_date = date_pats[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):
    """Crawl list pages and detail pages"""
    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, page)
        print(f"  -> 解析到 {len(items)} 条", flush=True)
        total_listed += len(items)

        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):
    """Output as JSONL"""
    count = 0
    with open(output_path, "w", encoding="utf-8") as f:
        for r in results:
            site_name = "和合承德网-公告通知"
            source_url = r["source_url"]
            item_id = hashlib.md5(source_url.encode()).hexdigest()

            record = {
                "id": item_id,
                "title": r["title"] or r["list_title"],
                "site_name": site_name,
                "source_url": 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=MAX_PAGES, help="爬取页数")
    parser.add_argument("--output", default="", help="输出文件路径")
    parser.add_argument("--page-start", type=int, default=1, help="起始页")
    parser.add_argument("--page-end", type=int, default=None, help="结束页")
    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/hehechengde_txy_{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)
