"""
mark2pdf CLI

主命令行接口，提供工作区管理和 Markdown 转 PDF 功能。
"""

import sys
from pathlib import Path

import click

from mark2pdf.core.utils import merge_frontmatter
from mark2pdf.helper_markdown import extract_frontmatter

from .commands import clean, compress, coverimg, fonts, gaozhi, init, mdimage, template, version
from .config import (
    ConfigManager,
    load_frontmatter_yaml,
    print_config_report,
    print_execution_plan,
    resolve_template,
)
from .conversion import run_batch_conversion, run_conversion, run_directory_conversion
from .process_builder import build_postprocessor_chain, get_processor_names_from_flags


@click.group()
def main():
    """mark2pdf - Markdown 转 PDF 工具集"""
    pass


# 注册子命令
main.add_command(clean)
main.add_command(compress)
main.add_command(coverimg)
main.add_command(fonts)
main.add_command(gaozhi)
main.add_command(mdimage)
main.add_command(init)
main.add_command(template)
main.add_command(version)


@main.command()
@click.argument("filename", required=False, default="index.md")
@click.option("--dir", "-d", "directory", help="目录合并模式：合并目录中所有 Markdown 并转换")
@click.option("--batch", "-b", "batch_dir", help="批量模式：逐一转换目录中每个 Markdown")
@click.option("--batchall", is_flag=True, help="批量模式：等价于 --batch .")
@click.option("--template", "-t", help="指定模板文件")
@click.option("--tc", is_flag=True, help="转换为繁体中文")
@click.option("--removelink", is_flag=True, help="移除链接（保留图片）")
@click.option("--open", "-o", "open_file", is_flag=True, help="转换完成后打开文件")
@click.option("--verbose", "-v", is_flag=True, help="显示详细信息")
@click.option("--overwrite", is_flag=True, help="覆盖输出文件（不添加时间戳）")
@click.option("--postprocess", "-p", help="后处理器名称（预留）")
@click.option("--show-config", is_flag=True, help="仅显示配置，不执行转换")
@click.option("--dry-run", is_flag=True, help="试运行模式，显示配置和执行计划")
@click.option("--force-filename", is_flag=True, help="强制使用原始文件名（忽略 exportFilename）")
def convert(
    filename: str,
    directory: str | None,
    batch_dir: str | None,
    batchall: bool,
    template: str | None,
    tc: bool,
    removelink: bool,
    open_file: bool,
    verbose: bool,
    overwrite: bool,
    postprocess: str | None,
    show_config: bool,
    dry_run: bool,
    force_filename: bool,
):
    """转换 Markdown 为 PDF

    使用方式：
        mark2pdf convert sample.md              # 转换单个文件
        mark2pdf convert --dir docs             # 合并目录转换
        mark2pdf convert --batch .              # 批量转换目录中所有文件
        mark2pdf convert --batchall             # 批量转换当前目录
    """

    if batchall:
        if batch_dir:
            click.echo("错误: --batchall 与 --batch 不能同时使用", err=True)
            sys.exit(1)
        batch_dir = "."

    # 加载完整配置（支持独立模式）
    config = ConfigManager.load()
    workspace = config.data_root or Path.cwd()
    if verbose:
        if config.standalone:
            click.echo("⚠️  未检测到工作区配置，使用独立模式")
        else:
            click.echo(f"📂 工作区: {workspace}")

    # 构建后处理器链
    processor_names = get_processor_names_from_flags(removelink, tc, postprocess)
    final_postprocess = build_postprocessor_chain(processor_names, verbose)



    # 加载 frontmatter.yaml
    default_fm = load_frontmatter_yaml(workspace)
    if config.frontmatter:
        default_fm = merge_frontmatter(config.frontmatter, default_fm)

    # 确定输入文件路径并读取 frontmatter
    if directory:
        input_path = config.input_dir / directory / "index.md"
    else:
        input_path = config.input_dir / filename

    file_fm = extract_frontmatter(input_path) if input_path.exists() else {}

    # 合并 frontmatter（文件覆盖默认）
    merged_fm = merge_frontmatter(default_fm, file_fm)

    # 解析最终模板
    final_template = resolve_template(
        cli_template=template,
        frontmatter_template=merged_fm.get("theme", {}).get("template"),
        config_template=config.options.default_template,
    )

    # 合并最终配置
    final_overwrite = overwrite or config.options.overwrite

    # --show-config / --dry-run / --verbose: 显示配置
    if show_config or dry_run or verbose:
        cli_params = {
            "filename": filename if not directory else None,
            "directory": directory,
            "batch_dir": batch_dir,
            "template": template,
            "tc": tc,
            "removelink": removelink,
            "overwrite": overwrite,
            "postprocess": postprocess,
            "force_filename": force_filename,
        }
        print_config_report(
            config=config,
            cli_params=cli_params,
            merged_fm=merged_fm,
            final_template=final_template,
            final_overwrite=final_overwrite,
            tc=tc,
        )

        if show_config:
            return

    # --dry-run: 显示执行计划后退出
    if dry_run:
        print_execution_plan(directory, batch_dir, filename)
        return

    # 执行转换
    if directory and batch_dir:
        click.echo("错误: --dir 和 --batch/--batchall 不能同时使用", err=True)
        sys.exit(1)

    success = False
    if directory:
        success = run_directory_conversion(
            directory=directory,
            workspace_dir=workspace,
            verbose=verbose,
            overwrite=overwrite,
            template=template,
            postprocess=final_postprocess,
            open_file=open_file,
            tc=tc,
            force_filename=force_filename,
        )
    elif batch_dir:
        success = run_batch_conversion(
            directory=batch_dir,
            workspace_dir=workspace,
            verbose=verbose,
            overwrite=overwrite,
            template=template,
            postprocess=final_postprocess,
            open_file=open_file,
            tc=tc,
            force_filename=force_filename,
        )
    else:
        success = run_conversion(
            filename=filename,
            workspace_dir=workspace,
            verbose=verbose,
            overwrite=overwrite,
            template=template,
            postprocess=final_postprocess,
            open_file=open_file,
            tc=tc,
            force_filename=force_filename,
        )

    if not success:
        sys.exit(1)


if __name__ == "__main__":
    main()
