"""
DOCX 处理命令行接口

用法示例：
  python -m file_parse.docx_worker.cli input.docx
  python -m file_parse.docx_worker.cli input.docx -l 1 --max-size 3000 --min-size 50
  python -m file_parse.docx_worker.cli input.docx -o ./output
"""

import argparse
import json
import sys
from datetime import datetime
from pathlib import Path

from ..interfaces import DocumentSource
from .pipeline import DocxPipeline


def main():
    parser = argparse.ArgumentParser(description="DOCX 文档处理工具")
    parser.add_argument("docx_path", help="输入 DOCX 文件路径")
    parser.add_argument(
        "-l", "--level",
        type=int,
        help="目标层级（默认从配置读取）"
    )
    parser.add_argument(
        "--max-size",
        type=int,
        help="最大块大小（默认从配置读取）"
    )
    parser.add_argument(
        "--min-size",
        type=int,
        help="最小块大小（默认从配置读取）"
    )
    parser.add_argument(
        "-o", "--output",
        help="输出目录（默认为 ./output）"
    )
    
    args = parser.parse_args()

    # 检查文件是否存在
    docx_path = Path(args.docx_path)
    if not docx_path.exists():
        print(f"错误：文件不存在 -> {docx_path}", file=sys.stderr)
        sys.exit(1)

    # 创建输出目录
    output_dir = Path(args.output) if args.output else Path("./output")
    output_dir.mkdir(parents=True, exist_ok=True)

    # 创建文档源
    source = DocumentSource(path=docx_path, file_type="docx")

    # 运行处理流程
    try:
        pipeline = DocxPipeline()
        result = pipeline.run(
            source,
            target_level=args.level,
            max_chunk_size=args.max_size,
            min_chunk_size=args.min_size,
        )
    except Exception as e:
        print(f"处理失败：{e}", file=sys.stderr)
        import traceback
        traceback.print_exc()
        sys.exit(1)

    # 生成输出文件名
    timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
    base_name = docx_path.stem
    output_file = output_dir / f"{base_name}_完整结果_{timestamp}.json"

    # 构建完整输出结构
    output_data = {
        "source_file": str(docx_path.absolute()),
        "process_time": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
        "toc_summary": {
            "total_items": result["toc_info"]["toc_count"],
            "toc_pages": result["toc_info"]["toc_pages"],
        },
        "complete_toc_list": [
            {
                "index": i + 1,
                "title": item["title"],
                "page": item["page"],
                "level": item["level"],
                "original": item["original"],
            }
            for i, item in enumerate(result["toc_info"]["toc_items"])
        ],
        "classification_summary": {
            "target_level": result["meta"]["target_level"],
            "total_count": result["classification"]["total_count"],
            "categories": result["classification"].get("category_stats", {}),
        },
        "classified_items": result["classification"]["items"],
        "chunks": result["chunks"],
        "meta": result["meta"],
    }

    # 写入文件
    with output_file.open("w", encoding="utf-8") as f:
        json.dump(output_data, f, ensure_ascii=False, indent=2)

    print(f"\n处理完成！")
    print(f"  输出文件: {output_file}")
    print(f"  目录项数: {result['toc_info']['toc_count']}")
    print(f"  分类项数: {result['classification']['total_count']}")
    print(f"  文本块数: {len(result['chunks'])}")


if __name__ == "__main__":
    main()
