#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
extract_source_assets.py —— 从用户提供的 Word/PPT/PDF/Excel/图片 抽取「文字 + 图片」作为 PPT 生成的高权重素材。

为什么需要
==========
ppt 工作流（workflows/ppt.yaml）支持「一段描述 + 任意素材（Word/PPT/Excel/PDF/图片，可多种混合）」→ 生成 PPT。客户素材里的
**文字是内容主干、图片要高权重复用**。这类机械抽取（unzip/遍历 shape/关联章节/取原始宽高比）
交给弱模型手搓不可靠，故收归确定性脚本——同 image_plan_lint.py / deck_pages_check.py 的哲学：
确定性的活脚本干，LLM 只做判断。

抽什么
======
- 文字：pptx 逐 slide / docx 逐 heading 段落（老 .doc 先转 docx）/ pdf 逐页 / xlsx 逐 sheet（openpyxl）/ csv·tsv（pandas）→ markdown 表，
  落 `source.md`（保留章节标题层级）。
- 图片：pptx 逐 picture shape / docx 的 word/media（按文档顺序关联最近 heading）/ pdf 逐页内嵌图 /
  xlsx 的 xl/media（纯 zipfile、免 openpyxl）/ **独立图片文件**（用户直接给的 png/jpg/…），
  落 `assets/src_K.png`（K 从 1 连续编号；与 AI 图 img_K.png 同目录、src_ 前缀区分）。
- 每张图记 **原始宽高比 + 朝向 + 所属章节 + 邻近文案**（manifest），供下游「等比不裁切 + 按朝向图文混排」。

产物（落到 --out 目录，默认 ./build）
====================================
- source.md            : 抽取正文（markdown，按 slide/heading/page 分节）
- assets/src_K.<ext>   : 抽取图片（保留原生扩展名，不重编码不失真）
- source_assets.json   : manifest（机读，驱动下游 design/build）：
    {"has_source":bool, "sources":[...], "text_file":"source.md",
     "images":[{"file":"src_1.png","w":1600,"h":900,"aspect_ratio":1.78,
                "orient":"landscape|portrait|square","section":"产品概览",
                "near_text":"…","origin":"brief.pptx#slide3"}]}

用法
====
    python extract_source_assets.py <doc-or-dir> [--out ./build] [-v]
    python extract_source_assets.py --scan <dir> [--out ./build]   # 目录里自动找 *.pptx/*.doc/*.docx/*.pdf
找不到任何源素材 → 写 has_source:false 的 manifest，**退出 0**（不报错，下游据此走纯 topic 路径）。

依赖：python-pptx / python-docx / Pillow（pptx+docx+图片，已就绪）；pandas（csv/tsv，已就绪）；
      openpyxl（xlsx 文字可选，缺则跳过文字仍抽内嵌图 + 提示安装）；pypdf（pdf 可选，缺则跳过 + 提示安装）。
"""

import argparse
import glob
import hashlib
import io
import json
import os
import shutil
import subprocess
import sys
import tempfile
import zipfile

# 文档类（抽文字 + 内嵌图）+ 表格类 + 独立图片类。三类都参与 --scan / 单文件识别。
DOC_EXTS = (".pptx", ".doc", ".docx", ".pdf", ".xlsx", ".csv", ".tsv")
IMAGE_EXTS = (".png", ".jpg", ".jpeg", ".gif", ".webp", ".bmp", ".tif", ".tiff")
SUPPORTED_EXTS = DOC_EXTS + IMAGE_EXTS
LANDSCAPE_MIN = 1.25  # w/h ≥ 此值 = 横图
PORTRAIT_MAX = 0.80   # w/h ≤ 此值 = 竖图（之间 = 近方图）
NEAR_TEXT_LIMIT = 240  # 邻近文案截断长度（manifest 不灌长文）


def _log(verbose: bool, msg: str) -> None:
    if verbose:
        print(f"[extract] {msg}", file=sys.stderr)


def _orient(w: int, h: int) -> str:
    if not w or not h:
        return "square"
    ar = w / h
    if ar >= LANDSCAPE_MIN:
        return "landscape"
    if ar <= PORTRAIT_MAX:
        return "portrait"
    return "square"


def _image_size(blob: bytes):
    """用 PIL 读原生宽高（失败返回 (0,0)，不让单张坏图拖垮整体）。"""
    try:
        from PIL import Image  # 延迟导入：缺 Pillow 时仍能抽文字
        with Image.open(io.BytesIO(blob)) as im:
            return int(im.width), int(im.height)
    except Exception:
        return 0, 0


def _save_image(blob: bytes, ext: str, out_assets: str, index: int):
    """把图片 blob 落盘为 assets/src_K.<ext>（保留原生格式，不重编码避免失真）。返回 (file, w, h)。"""
    ext = (ext or "png").lower().lstrip(".")
    if ext == "jpeg":
        ext = "jpg"
    if ext not in ("png", "jpg", "gif", "bmp", "tiff", "webp", "emf", "wmf"):
        ext = "png"
    fname = f"src_{index}.{ext}"
    with open(os.path.join(out_assets, fname), "wb") as f:
        f.write(blob)
    w, h = _image_size(blob)
    return fname, w, h


def _truncate(text: str) -> str:
    text = " ".join((text or "").split())
    return text[:NEAR_TEXT_LIMIT]


# ---------------------------------------------------------------------------
# pptx：逐 slide 抽文字 + picture shape 抽图
# ---------------------------------------------------------------------------
def _extract_pptx(path, out_assets, md_lines, images, start_index, verbose):
    from pptx import Presentation
    from pptx.enum.shapes import MSO_SHAPE_TYPE

    prs = Presentation(path)
    base = os.path.basename(path)
    idx = start_index

    def walk_pictures(shapes):
        """递归收集 picture（含 group 内嵌套图）。"""
        for sh in shapes:
            if sh.shape_type == MSO_SHAPE_TYPE.GROUP:
                yield from walk_pictures(sh.shapes)
            elif sh.shape_type == MSO_SHAPE_TYPE.PICTURE:
                yield sh

    for sn, slide in enumerate(prs.slides, 1):
        # 该页文字（标题优先）
        title = ""
        texts = []
        for sh in slide.shapes:
            if not sh.has_text_frame:
                continue
            t = sh.text_frame.text.strip()
            if not t:
                continue
            if not title and sh == getattr(slide.shapes, "title", None):
                title = t.splitlines()[0]
            texts.append(t)
        section = title or f"第 {sn} 页"
        md_lines.append(f"\n## Slide {sn}：{section}\n")
        for t in texts:
            for line in t.splitlines():
                line = line.strip()
                if line:
                    md_lines.append(f"- {line}")
        near = _truncate(" ".join(texts))

        # 该页图片
        for sh in walk_pictures(slide.shapes):
            try:
                img = sh.image
                fname, w, h = _save_image(img.blob, img.ext, out_assets, idx)
                images.append({
                    "file": fname, "w": w, "h": h,
                    "aspect_ratio": round(w / h, 4) if w and h else 0,
                    "orient": _orient(w, h),
                    "section": section, "near_text": near,
                    "origin": f"{base}#slide{sn}",
                })
                _log(verbose, f"pptx slide{sn} 图 {fname} {w}x{h} {_orient(w, h)}")
                idx += 1
            except Exception as e:  # 单张坏图不拖垮整体
                _log(verbose, f"pptx slide{sn} 跳过一张图：{e}")
    return idx


# ---------------------------------------------------------------------------
# docx：按文档顺序遍历段落，跟踪当前 heading，blip 关联最近 heading
# ---------------------------------------------------------------------------
def _extract_docx(path, out_assets, md_lines, images, start_index, verbose):
    from docx import Document

    doc = Document(path)
    base = os.path.basename(path)
    idx = start_index
    seen_hashes = set()
    ns_r = "{http://schemas.openxmlformats.org/officeDocument/2006/relationships}"
    ns_a = "{http://schemas.openxmlformats.org/drawingml/2006/main}"
    current_section = "正文"
    recent_text = []  # 最近几段正文（给图片当 near_text）

    for para in doc.paragraphs:
        style = (para.style.name or "") if para.style else ""
        text = para.text.strip()
        if style.lower().startswith("heading") and text:
            current_section = text
            level = "".join(ch for ch in style if ch.isdigit()) or "2"
            md_lines.append(f"\n{'#' * min(int(level) + 1, 6)} {text}\n")
            recent_text = []
        elif text:
            md_lines.append(text)
            recent_text.append(text)
            recent_text = recent_text[-3:]

        # 该段内嵌图（a:blip r:embed → rId → image part）
        for blip in para._p.findall(f".//{ns_a}blip"):
            rid = blip.get(f"{ns_r}embed")
            if not rid or rid not in doc.part.related_parts:
                continue
            try:
                part = doc.part.related_parts[rid]
                blob = part.blob
                seen_hashes.add(hashlib.sha1(blob).hexdigest())
                ext = os.path.splitext(part.partname)[1] or ".png"
                fname, w, h = _save_image(blob, ext, out_assets, idx)
                images.append({
                    "file": fname, "w": w, "h": h,
                    "aspect_ratio": round(w / h, 4) if w and h else 0,
                    "orient": _orient(w, h),
                    "section": current_section,
                    "near_text": _truncate(" ".join(recent_text) or text),
                    "origin": f"{base}#{current_section}",
                })
                _log(verbose, f"docx 图 {fname} {w}x{h} {_orient(w, h)} @ {current_section}")
                idx += 1
            except Exception as e:
                _log(verbose, f"docx 跳过一张图：{e}")

    # 兜底：部分 Word 里的浮动图、形状图或兼容模式转换图不一定出现在段落
    # blip 遍历里，但会存在于 word/media。补扫一次并按 hash 去重。
    try:
        with zipfile.ZipFile(path) as z:
            names = sorted(
                n for n in z.namelist()
                if n.startswith("word/media/") and not n.endswith("/")
            )
            for n in names:
                try:
                    blob = z.read(n)
                    hsh = hashlib.sha1(blob).hexdigest()
                    if hsh in seen_hashes:
                        continue
                    seen_hashes.add(hsh)
                    ext = os.path.splitext(n)[1] or ".png"
                    fname, w, h = _save_image(blob, ext, out_assets, idx)
                    images.append({
                        "file": fname, "w": w, "h": h,
                        "aspect_ratio": round(w / h, 4) if w and h else 0,
                        "orient": _orient(w, h),
                        "section": current_section or "文档内嵌图",
                        "near_text": _truncate(" ".join(recent_text)),
                        "origin": f"{base}#{os.path.basename(n)}",
                    })
                    _log(verbose, f"docx word/media 兜底图 {fname} {w}x{h} {_orient(w, h)}")
                    idx += 1
                except Exception as e:
                    _log(verbose, f"docx word/media 跳过一张图：{e}")
    except Exception as e:
        _log(verbose, f"docx word/media 兜底读取失败：{e}")
    return idx


def _find_soffice():
    """定位 LibreOffice/soffice 可执行文件。

    为什么不能只 shutil.which：LibreOffice 在 Windows 默认装到
    `C:\\Program Files\\LibreOffice\\program\\soffice.exe` 但**不会自动进 PATH**，
    macOS 装进 .app 包内、Linux 有时落 /opt——`which` 只查 PATH 全都漏掉，
    于是「明明装了却报未找到」（真机 K1 同款：bash.ts 探 Git Bash 也是这套路）。
    顺序：env 显式覆盖 → PATH → 各平台标准安装位置（含通配）。找不到返回 None。
    """
    env = os.environ.get("MINIMAL_AGENT_SOFFICE") or os.environ.get("SOFFICE_PATH")
    if env and os.path.isfile(env):
        return env
    found = shutil.which("soffice") or shutil.which("libreoffice")
    if found:
        return found
    candidates = [
        # Windows
        r"C:\Program Files\LibreOffice\program\soffice.exe",
        r"C:\Program Files (x86)\LibreOffice\program\soffice.exe",
        # macOS
        "/Applications/LibreOffice.app/Contents/MacOS/soffice",
        # Linux 常见落点
        "/usr/bin/soffice",
        "/usr/bin/libreoffice",
        "/snap/bin/libreoffice",
    ]
    # Linux /opt 下带版本号目录用通配兜底
    candidates.extend(sorted(glob.glob("/opt/libreoffice*/program/soffice")))
    for c in candidates:
        if os.path.isfile(c):
            return c
    return None


def _convert_doc_to_docx(path, verbose):
    """用 LibreOffice headless 把老 .doc 转成临时 .docx。返回临时 docx 路径。"""
    soffice = _find_soffice()
    if not soffice:
        raise RuntimeError(
            "无法转换 .doc：未找到 LibreOffice/soffice（PATH 与标准安装位置均无）。"
            "请安装 LibreOffice，或设环境变量 MINIMAL_AGENT_SOFFICE 指向 soffice 可执行文件，"
            "或先把 .doc 另存为 .docx 再试。"
        )
    tmp = tempfile.mkdtemp(prefix="extract-doc-")
    cmd = [
        soffice,
        "--headless",
        "--convert-to",
        "docx",
        "--outdir",
        tmp,
        path,
    ]
    _log(verbose, f"转换 .doc → .docx: {' '.join(cmd)}")
    try:
        result = subprocess.run(
            cmd,
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE,
            text=True,
            encoding="utf-8",  # soffice 中文输出：不显式 UTF-8 则中文 Windows 走 GBK 解码崩
            errors="replace",
            timeout=120,
            check=False,
        )
    except subprocess.TimeoutExpired as e:
        raise RuntimeError("转换 .doc 超时（LibreOffice 120s 未返回）") from e
    if result.returncode != 0:
        detail = (result.stderr or result.stdout or "").strip()
        raise RuntimeError(f"转换 .doc 失败（exit {result.returncode}）：{detail}")
    base = os.path.splitext(os.path.basename(path))[0] + ".docx"
    converted = os.path.join(tmp, base)
    if not os.path.isfile(converted):
        matches = [
            os.path.join(tmp, f)
            for f in os.listdir(tmp)
            if f.lower().endswith(".docx")
        ]
        if matches:
            converted = matches[0]
        else:
            detail = (result.stdout or result.stderr or "").strip()
            raise RuntimeError(f"转换 .doc 后未找到 docx 产物：{detail}")
    return converted


def _extract_doc(path, out_assets, md_lines, images, start_index, verbose):
    converted = _convert_doc_to_docx(path, verbose)
    md_lines.append(f"\n> 老 Word `.doc` 已通过 LibreOffice 转换为 `.docx` 后抽取：{os.path.basename(converted)}\n")
    return _extract_docx(converted, out_assets, md_lines, images, start_index, verbose)


# ---------------------------------------------------------------------------
# pdf：pypdf 可选；缺库优雅跳过 + 提示安装
# ---------------------------------------------------------------------------
def _extract_pdf(path, out_assets, md_lines, images, start_index, verbose):
    try:
        from pypdf import PdfReader
    except ImportError:
        print(
            "[extract] 跳过 PDF（未装 pypdf）。如需支持 PDF 素材：pip install pypdf",
            file=sys.stderr,
        )
        return start_index

    reader = PdfReader(path)
    base = os.path.basename(path)
    idx = start_index
    for pn, page in enumerate(reader.pages, 1):
        try:
            text = (page.extract_text() or "").strip()
        except Exception:
            text = ""
        md_lines.append(f"\n## 第 {pn} 页\n")
        if text:
            md_lines.append(text)
        near = _truncate(text)
        try:
            page_images = list(page.images)
        except Exception:
            page_images = []
        for im in page_images:
            try:
                blob = im.data
                ext = os.path.splitext(im.name or "")[1] or ".png"
                fname, w, h = _save_image(blob, ext, out_assets, idx)
                images.append({
                    "file": fname, "w": w, "h": h,
                    "aspect_ratio": round(w / h, 4) if w and h else 0,
                    "orient": _orient(w, h),
                    "section": f"第 {pn} 页", "near_text": near,
                    "origin": f"{base}#page{pn}",
                })
                _log(verbose, f"pdf page{pn} 图 {fname} {w}x{h}")
                idx += 1
            except Exception as e:
                _log(verbose, f"pdf page{pn} 跳过一张图：{e}")
    return idx


# ---------------------------------------------------------------------------
# OOXML 内嵌图通用抽取（zip 里的 media 目录）——免第三方库，xlsx 缺 openpyxl 时仍能抽图
# ---------------------------------------------------------------------------
def _extract_ooxml_media(path, base, media_prefix, section, out_assets, images, start_index, verbose):
    idx = start_index
    try:
        with zipfile.ZipFile(path) as z:
            names = sorted(
                n for n in z.namelist() if n.startswith(media_prefix) and not n.endswith("/")
            )
            for n in names:
                try:
                    blob = z.read(n)
                    ext = os.path.splitext(n)[1] or ".png"
                    fname, w, h = _save_image(blob, ext, out_assets, idx)
                    images.append({
                        "file": fname, "w": w, "h": h,
                        "aspect_ratio": round(w / h, 4) if w and h else 0,
                        "orient": _orient(w, h),
                        "section": section, "near_text": "",
                        "origin": f"{base}#{os.path.basename(n)}",
                    })
                    _log(verbose, f"{base} 内嵌图 {fname} {w}x{h} {_orient(w, h)}")
                    idx += 1
                except Exception as e:
                    _log(verbose, f"{base} 跳过一张内嵌图：{e}")
    except Exception as e:
        _log(verbose, f"{base} 读取内嵌图失败：{e}")
    return idx


# ---------------------------------------------------------------------------
# csv / tsv：pandas → markdown 表（无图）
# ---------------------------------------------------------------------------
def _extract_csv(path, out_assets, md_lines, images, start_index, verbose):
    import pandas as pd

    base = os.path.basename(path)
    sep = "\t" if path.lower().endswith(".tsv") else ","
    df = pd.read_csv(path, sep=sep, dtype=str, keep_default_na=False)
    cap = 50
    md_lines.append(f"\n## 表格：{base}（{len(df)} 行 × {len(df.columns)} 列）\n")
    cols = [str(c) for c in df.columns]
    md_lines.append("| " + " | ".join(cols) + " |")
    md_lines.append("| " + " | ".join("---" for _ in cols) + " |")
    for _, row in df.head(cap).iterrows():
        cells = [str(v).replace("|", "\\|").replace("\n", " ") for v in row]
        md_lines.append("| " + " | ".join(cells) + " |")
    if len(df) > cap:
        md_lines.append(f"\n（共 {len(df)} 行，上表仅前 {cap} 行）")
    _log(verbose, f"csv/tsv {base} {len(df)}x{len(df.columns)}")
    return start_index


# ---------------------------------------------------------------------------
# xlsx：openpyxl 抽表文字（缺则跳过文字、仍用 zipfile 抽内嵌图）
# ---------------------------------------------------------------------------
def _extract_xlsx(path, out_assets, md_lines, images, start_index, verbose):
    base = os.path.basename(path)
    try:
        from openpyxl import load_workbook

        wb = load_workbook(path, read_only=True, data_only=True)
        cap = 50
        for ws in wb.worksheets:
            md_lines.append(f"\n## 工作表：{ws.title}\n")
            rows = list(ws.iter_rows(values_only=True))
            header_done = False
            for row in rows[:cap]:
                cells = ["" if v is None else str(v) for v in row]
                if not any(c.strip() for c in cells):
                    continue
                safe = [c.replace("|", "\\|").replace("\n", " ") for c in cells]
                md_lines.append("| " + " | ".join(safe) + " |")
                if not header_done:
                    md_lines.append("| " + " | ".join("---" for _ in safe) + " |")
                    header_done = True
            if len(rows) > cap:
                md_lines.append(f"\n（共 {len(rows)} 行，上表仅前 {cap} 行）")
        wb.close()
    except ImportError:
        print(
            "[extract] xlsx 文字跳过（未装 openpyxl）。如需表格文字：pip install openpyxl",
            file=sys.stderr,
        )
        md_lines.append(f"\n## 表格：{base}（未装 openpyxl，未抽文字；如需 pip install openpyxl）\n")
    except Exception as e:
        _log(verbose, f"xlsx 文字抽取失败：{e}")
    # 内嵌图：xlsx 是 OOXML zip，xl/media/* 即内嵌图（免 openpyxl）
    return _extract_ooxml_media(
        path, base, "xl/media/", "工作簿", out_assets, images, start_index, verbose
    )


# ---------------------------------------------------------------------------
# 独立图片：用户直接给的 png/jpg/…（每张当一个 source 图，section=文件名）
# ---------------------------------------------------------------------------
def _extract_image(path, out_assets, md_lines, images, start_index, verbose):
    base = os.path.basename(path)
    section = os.path.splitext(base)[0]
    idx = start_index
    try:
        with open(path, "rb") as f:
            blob = f.read()
        ext = os.path.splitext(path)[1] or ".png"
        fname, w, h = _save_image(blob, ext, out_assets, idx)
        images.append({
            "file": fname, "w": w, "h": h,
            "aspect_ratio": round(w / h, 4) if w and h else 0,
            "orient": _orient(w, h),
            "section": section, "near_text": "",
            "origin": base,
        })
        md_lines.append(f"\n## 图片：{base}\n")
        md_lines.append(f"（用户提供的图片，见 assets/{fname}）")
        _log(verbose, f"独立图片 {fname} {w}x{h} {_orient(w, h)}")
        idx += 1
    except Exception as e:
        _log(verbose, f"图片 {base} 抽取失败：{e}")
    return idx


_EXTRACTORS = {
    ".pptx": _extract_pptx,
    ".doc": _extract_doc,
    ".docx": _extract_docx,
    ".pdf": _extract_pdf,
    ".xlsx": _extract_xlsx,
    ".csv": _extract_csv,
    ".tsv": _extract_csv,
}
# 独立图片各扩展名都走 _extract_image
for _ie in IMAGE_EXTS:
    _EXTRACTORS[_ie] = _extract_image


def discover_sources(target: str, scan: bool):
    """target 是文件 → [它]；是目录或 --scan → 目录内所有受支持文档（排序，稳定）。"""
    if os.path.isfile(target):
        return [target] if target.lower().endswith(SUPPORTED_EXTS) else []
    if os.path.isdir(target) or scan:
        d = target if os.path.isdir(target) else "."
        found = [
            os.path.join(d, f)
            for f in sorted(os.listdir(d))
            if f.lower().endswith(SUPPORTED_EXTS) and not f.startswith("~$")
        ]
        return found
    return []


def extract(target: str, out_dir: str, scan: bool = False, verbose: bool = False):
    """主流程。返回 manifest dict（同时落盘 source.md / assets/ / source_assets.json）。"""
    out_dir = os.path.abspath(out_dir)
    out_assets = os.path.join(out_dir, "assets")
    os.makedirs(out_assets, exist_ok=True)

    sources = discover_sources(target, scan)
    md_lines = []
    images = []
    idx = 1
    used_sources = []

    for src in sources:
        ext = os.path.splitext(src)[1].lower()
        fn = _EXTRACTORS.get(ext)
        if not fn:
            continue
        md_lines.append(f"\n# 来源：{os.path.basename(src)}\n")
        try:
            idx = fn(src, out_assets, md_lines, images, idx, verbose)
            used_sources.append(os.path.basename(src))
        except Exception as e:
            print(f"[extract] 抽取 {src} 失败（跳过该文档）：{e}", file=sys.stderr)

    has_source = bool(used_sources)
    if has_source:
        with open(os.path.join(out_dir, "source.md"), "w", encoding="utf-8") as f:
            f.write("\n".join(md_lines).strip() + "\n")

    manifest = {
        "has_source": has_source,
        "sources": used_sources,
        "text_file": "source.md" if has_source else None,
        "images": images,
    }
    with open(os.path.join(out_dir, "source_assets.json"), "w", encoding="utf-8") as f:
        json.dump(manifest, f, ensure_ascii=False, indent=2)
    return manifest


def main() -> int:
    parser = argparse.ArgumentParser(
        description="从 Word/PPT/Excel/PDF/图片 抽取文字+图片作为 PPT 生成素材（确定性）"
    )
    parser.add_argument("target", help="源素材路径（文档/表格/图片），或含素材的目录")
    parser.add_argument("--out", default="./build", help="输出目录（默认 ./build）")
    parser.add_argument("--scan", action="store_true", help="把 target 当目录扫描所有受支持文档")
    parser.add_argument("-v", "--verbose", action="store_true", help="打印逐张图/逐节进度到 stderr")
    args = parser.parse_args()

    manifest = extract(args.target, args.out, args.scan, args.verbose)
    if manifest["has_source"]:
        print(
            f"SOURCE_EXTRACTED: {len(manifest['sources'])} 个文档、"
            f"{len(manifest['images'])} 张图片 → {os.path.join(args.out, 'source_assets.json')}"
        )
    else:
        print("NO_SOURCE: 未发现可抽取的素材（Word/PPT/Excel/PDF/图片）（下游按纯 topic 生成）")
    return 0


if __name__ == "__main__":
    sys.exit(main())
