import shutil
from pathlib import Path

from triclick_doc_toolset.service import run_generation, run_pipeline


INPUT_DIR = Path(__file__).resolve().parent / "data.input"
PIPELINES_DIR = Path(__file__).resolve().parents[1] / "pipelines"
GEN_CFG = str(PIPELINES_DIR / "generation.yaml")
OUTPUT_DIR = str(Path(__file__).resolve().parent / "data.output")

# UV_INDEX_URL=https://pypi.org/simple/ PYTHONPATH=src uv run --with pytest,python-docx,pyyaml,pydantic pytest -q -rs tests/test_service.py 

def test_run_generation_on_single_docx_files():
    filenames = [
        "generation_shell.docx",
        "generation_shell0.docx",
        "generation_shell1.docx",
        "generation_shell2.docx",
        "generation_shell3.docx",
        "generation_shell5.docx",
    ]
    for fname in filenames:
        doc_path = INPUT_DIR / fname
        assert doc_path.exists(), f"Test input file missing: {doc_path}"

        result = run_generation(str(doc_path), output_dir=OUTPUT_DIR)

        # 基本结构
        assert isinstance(result, dict)
        assert result.get("doc_type") == "docx"

        # 元数据包含源文件
        metadata = result.get("metadata", {})
        assert metadata.get("source_file") == str(doc_path)

        # sections 是列表
        sections = result.get("sections")
        assert isinstance(sections, list)

        # 处理摘要包含解析与拆分两个阶段
        summary = result.get("processing_summary", {})
        assert "title_table_footnote_partition" in summary
        assert "title_table_footnote_split" in summary

        part = summary["title_table_footnote_partition"]
        split = summary["title_table_footnote_split"]

        # 单文件输入应标记处理文件数为 1
        assert part.get("files_processed") == 1
        assert split.get("files_processed") == 1

        # 生成文件统计一致
        generated_files = result.get("generated_files", [])
        assert isinstance(generated_files, list)
        assert split.get("generated_files_count") == len(generated_files)

        # 输出目录存在
        for out_dir in split.get("output_dirs", []):
            assert Path(out_dir).exists()

        # 每个生成文件都在磁盘上
        for f in generated_files:
            assert Path(f).exists(), f"Generated file missing: {f}"

        # 清理输出目录，避免污染仓库
        for out_dir in split.get("output_dirs", []):
            p = Path(out_dir)
            if p.exists():
                shutil.rmtree(p)


def test_run_pipeline_rejects_comma_paths():
    # 逗号分隔路径应抛出错误
    bad_path = f"{INPUT_DIR}, {INPUT_DIR}"
    try:
        run_pipeline(GEN_CFG, bad_path, output_dir=OUTPUT_DIR)
    except ValueError:
        pass
    else:
        assert False, "Expected ValueError for comma-separated path"


def test_run_pipeline_missing_path_raises():
    # 不存在的文件路径应抛出 FileNotFoundError
    missing = INPUT_DIR / "nonexistent_file.docx"
    try:
        run_pipeline(GEN_CFG, str(missing), output_dir=OUTPUT_DIR)
    except FileNotFoundError:
        pass
    else:
        assert False, "Expected FileNotFoundError for missing path"