"""
mark2pdf 后处理器构建器

负责动态加载和组装后处理器链。
"""

from collections.abc import Callable

import click


def build_postprocessor_chain(
    processor_names: list[str],
    verbose: bool = False,
) -> Callable[[str], str] | None:
    """
    构建后处理器链

    根据处理器名称列表动态加载并组装成一个组合函数。

    Args:
        processor_names: 处理器名称列表，如 ["remove_links", "to_traditional_chinese"]
        verbose: 是否显示详细信息

    Returns:
        组合后的处理函数，如果列表为空则返回 None
    """
    if not processor_names:
        return None

    from mark2pdf.core.postprocess import load_postprocessor

    funcs = [load_postprocessor(p) for p in processor_names]
    funcs = [f for f in funcs if f]  # 过滤 None

    # 检查未找到的处理器
    missing = [
        p
        for p, f in zip(processor_names, [load_postprocessor(p) for p in processor_names])
        if f is None
    ]
    if missing:
        click.echo(f"⚠️  未找到处理器: {', '.join(missing)}", err=True)

    if not funcs:
        return None

    def combined(content: str) -> str:
        for fn in funcs:
            content = fn(content)
        return content

    if verbose:
        click.echo(f"📦 后处理器: {', '.join(processor_names)}")

    return combined


def get_processor_names_from_flags(
    removelink: bool = False,
    tc: bool = False,
    postprocess: str | None = None,
) -> list[str]:
    """
    从 CLI 标志构建处理器名称列表

    Args:
        removelink: 是否启用移除链接
        tc: 是否启用繁体转换
        postprocess: 自定义处理器名称

    Returns:
        处理器名称列表
    """
    processors = []
    if removelink:
        processors.append("remove_links")
    if tc:
        processors.append("to_traditional_chinese")
    if postprocess:
        processors.append(postprocess)
    return processors
