"""
PDF 处理命令行入口（基于 pdf_worker_adapter）

用法示例：

  python -m file_parse.pdf_worker.cli input.pdf

【修改记录】2025-03-27: 移除 MinerU 引擎选项，仅保留 hybrid 和 pdf
"""

from __future__ import annotations

import argparse
from pathlib import Path

from .adapter import build_pdf_facade, build_hybrid_facade


def main() -> None:
    parser = argparse.ArgumentParser(
        description="PDF 文档分类切分工具（基于 file_parse/pdf_worker）"
    )
    parser.add_argument("file_path", help="PDF 文件路径")

    parser.add_argument(
        "--engine",
        choices=["pdf", "hybrid"],
        default="hybrid",
        help="选择全文提取引擎：hybrid (智能混合模式，默认), pdf (纯本地 PyMuPDF)",
    )

    parser.add_argument(
        "-l",
        "--level",
        type=int,
        default=None,
        help="要分类的目标层级（默认读取配置 text_splitting.target_level）",
    )
    parser.add_argument(
        "--max-size",
        type=int,
        default=None,
        help="最大分块字符数（默认读取配置 text_splitting.max_chunk_size）",
    )
    parser.add_argument(
        "--min-size",
        type=int,
        default=None,
        help="最小分块字符数（默认读取配置 text_splitting.min_chunk_size）",
    )
    parser.add_argument(
        "-o",
        "--output",
        help="输出目录（可选，默认按配置 output.default_dir_name 放在源文件同目录）",
    )

    args = parser.parse_args()

    file_path = Path(args.file_path)
    if not file_path.exists():
        raise SystemExit(f"错误：文件不存在 -> {file_path}")
    
    supported_extensions = {".pdf", ".png", ".jpg", ".jpeg"}
    if file_path.suffix.lower() not in supported_extensions:
        raise SystemExit(f"当前 CLI 仅支持以下文件类型: {supported_extensions}")

    if args.engine == "hybrid":
        print("正在使用智能混合引擎（扫描件自动使用 GLM-OCR）...")
        facade = build_hybrid_facade()
    else:  # default to pdf
        print("正在使用本地 PyMuPDF 引擎...")
        facade = build_pdf_facade()
        
    result = facade.process_file(
        file_path=file_path,
        target_level=args.level,
        max_chunk_size=args.max_size,
        min_chunk_size=args.min_size,
        output_dir=args.output,
    )

    chunks = result.get("chunks", []) or []
    toc_info = result.get("toc_info", {}) or {}
    classification = result.get("classification", {}) or {}

    print("\n" + "=" * 80)
    print("处理完成")
    print("=" * 80)
    print(f"源文件: {file_path.name}")
    print(f"目录项数: {toc_info.get('toc_count', len(toc_info.get('toc_items', [])))}")
    print(f"文本块总数: {len(chunks)}")
    print(f"分类目标层级: {classification.get('target_level')}")


if __name__ == "__main__":
    main()
