#!/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.hanshou.gov.cn"
LIST_URL = f"{BASE_URL}/zwyw/tzgg"
MAX_PAGES = 180

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


# ─── 正文取文本（2026-09-11）：行内节点直接拼接，只在块级边界 / <br> 处换行 ───
# ⚠️ 不要用 el.get_text("\n") 取正文 —— 它是「每个**文本节点**之间插 \n」，Word 粘贴的
#    公文把一行拆成 <span>提取码：</span>pwaj<span>。查阅…</span>，这些行内节点于是各自
#    成行（福泉 id=2095080103703914437 实例：`提取码：`/`pwaj`/`。查阅…` 各占一行）。
_BLOCK_TAGS = {'address', 'article', 'aside', 'blockquote', 'details', 'dialog', 'dd', 'div',
               'dl', 'dt', 'fieldset', 'figcaption', 'figure', 'footer', 'form', 'h1', 'h2',
               'h3', 'h4', 'h5', 'h6', 'header', 'hgroup', 'hr', 'li', 'main', 'nav', 'ol',
               'p', 'pre', 'section', 'table', 'tbody', 'thead', 'tfoot', 'tr', 'td', 'th',
               'ul', 'center', 'caption'}


def body_text(el):
    """块级边界出换行、行内节点直接拼接、<br> 出换行（≈ 浏览器看到的换行结构）。"""
    if el is None:
        return ''
    import re as _re
    from bs4 import NavigableString
    out = []

    def walk(node):
        for ch in node.children:
            if isinstance(ch, NavigableString):
                out.append(str(ch))
            elif getattr(ch, 'name', None) == 'br':
                out.append('\n')
            elif getattr(ch, 'name', None) in _BLOCK_TAGS:
                out.append('\n')
                walk(ch)
                out.append('\n')
            else:
                walk(ch)
    walk(el)
    t = ''.join(out)
    t = _re.sub(r'[ \t\r\f\v]*\n[ \t\r\f\v]*', '\n', t)
    t = _re.sub(r'\n{3,}', '\n\n', t)
    return t.strip()


def make_session():
    s = requests.Session()
    s.headers.update(HEADERS)
    # Visit first page to get cookies
    try:
        s.get(LIST_URL, timeout=30)
    except Exception:
        pass
    return s


def get_list_url(page):
    if page <= 1:
        return LIST_URL
    return f"{BASE_URL}/zwyw/tzgg_{page}"


def parse_list_page(html, page):
    """Parse list page, return list of (url, title, date_str)"""
    items = []
    ulm = re.search(r'<ul[^>]*class="newsList"[^>]*>(.*?)</ul>', html, re.DOTALL)
    if not ulm:
        return items

    ul_html = ulm.group(1)
    li_pattern = re.compile(r'<li[^>]*>(.*?)</li>', re.DOTALL)

    for m in li_pattern.finditer(ul_html):
        li = m.group(1)
        # URL and title
        a_match = re.search(r'<a[^>]*href="([^"]+)"[^>]*title="([^"]*)"[^>]*>(.*?)</a>', li, re.DOTALL)
        if not a_match:
            continue
        href = a_match.group(1).strip()
        title_attr = a_match.group(2).strip()
        # Strip "标题：" prefix from title
        title = re.sub(r"^标题[：:]", "", title_attr).strip()
        if not title:
            # Fallback to link text
            link_text = re.sub(r'<[^>]+>', '', a_match.group(3)).strip()
            title = link_text

        # Date from span
        date_match = re.search(r'<span[^>]*class="date"[^>]*>(.*?)</span>', li, re.DOTALL)
        date_str = date_match.group(1).strip() if date_match else ""

        # Full URL
        if href.startswith("/"):
            full_url = f"{BASE_URL}{href}"
        elif not href.startswith("http"):
            full_url = f"{BASE_URL}/{href}"
        else:
            full_url = href

        items.append((full_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
    title_tag = soup.find("title")
    full_title = title_tag.get_text(strip=True) if title_tag else ""
    full_title = re.sub(r"_通知公告_政务要闻_汉寿县人民政府$", "", full_title).strip()

    # Content from conTxt div (or articleCon fallback)
    content_div = soup.find("div", class_="conTxt")
    if not content_div:
        content_div = soup.find("div", class_="articleCon")
    if not content_div:
        content_div = soup.find("div", class_="dt-text")
    if not content_div:
        # Fallback
        all_divs = soup.find_all("div")
        for d in all_divs:
            text = d.get_text(strip=True)
            if len(text) > 200:
                classes = d.get("class", [])
                if any(c in str(classes) for c in ["content", "article", "text", "main"]):
                    content_div = d
                    break

    content_html = ""
    attachments = []
    if content_div:
        # Extract attachments first
        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}"
                    elif href.startswith("//"):
                        href = f"https:{href}"
                    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 - 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 = body_text(child).strip()
                if text:
                    content_parts.append(text)
            elif tag_name == "div":
                text = body_text(child).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 = body_text(content_div)
        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"^【纠错】",
            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 = ""
    # Try meta tags first
    meta_date = soup.find("meta", attrs={"name": "publishdate"}) or soup.find("meta", attrs={"name": "PubDate"})
    if meta_date and meta_date.get("content"):
        pub_date = meta_date.get("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):
    """Crawl list pages and detail pages"""
    if page_end is None:
        page_end = max_pages

    session = make_session()
    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)

        if not items:
            print(f"  -> 无内容，停止翻页", flush=True)
            break

        for idx, (item_url, list_title, date_str) in enumerate(items, 1):
            print(f"  [{idx}/{len(items)}] {list_title[:60]}...", flush=True)
            try:
                # Refresh session for detail page
                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/hanshou_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)
