from pathlib import Path

from docx import Document

from app.main import OUTPUT_DIR, ROOT_DIR, analyze_saved_docx, app


def test_index_template_contains_upload_ui() -> None:
    html = (ROOT_DIR / "app" / "templates" / "index.html").read_text(encoding="utf-8")
    js = (ROOT_DIR / "app" / "static" / "app.js").read_text(encoding="utf-8")

    assert "DOCX 规范分析" in html
    assert 'type="file"' in html
    assert "analysis-progress" in html
    assert "analysis-status" in html
    assert "下载 Markdown 报告" in html
    assert "download-md" in js
    assert "pollTask" in js
    assert "skill_collection" in html
    assert "预留后续版本：单个技能集合内的 skill 筛选功能" in html
    assert not any(route.path == "/skills" for route in app.routes)


def test_analyze_saved_docx_reports_progress(tmp_path: Path) -> None:
    updates: list[tuple[int, str]] = []
    docx_path = tmp_path / "progress.docx"
    document = Document()
    document.add_heading("软件需求规格说明", level=1)
    document.add_paragraph("能力需求、接口需求、合格性规定。")
    document.save(docx_path)

    payload = analyze_saved_docx(
        docx_path,
        provider="deepseek",
        use_model=False,
        progress_callback=lambda progress, message: updates.append((progress, message)),
    )

    assert updates[0][0] == 5
    assert updates[-1] == (100, "分析完成")
    assert any("技能" in message for _, message in updates)
    assert payload["downloads"]["markdown"].endswith(".md")


def test_analyze_saved_docx_creates_downloadable_report(tmp_path: Path) -> None:
    docx_path = tmp_path / "upload.docx"
    document = Document()
    document.add_heading("软件需求规格说明", level=1)
    document.add_paragraph("能力需求、接口需求、合格性规定。")
    document.save(docx_path)

    payload = analyze_saved_docx(docx_path, provider="deepseek", use_model=False)

    assert payload["source_filename"] == "upload.docx"
    assert "docx" not in payload["downloads"]
    assert payload["downloads"]["markdown"].endswith(".md")
    assert (OUTPUT_DIR / Path(payload["downloads"]["markdown"]).name).exists()


def test_analyze_saved_docx_uses_selected_collection(tmp_path: Path) -> None:
    docx_path = tmp_path / "upload.docx"
    document = Document()
    document.add_heading("软件需求规格说明", level=1)
    document.add_paragraph("能力需求、接口需求、合格性规定。")
    document.save(docx_path)

    payload = analyze_saved_docx(
        docx_path,
        provider="deepseek",
        use_model=False,
        skill_collection="GJB438B-2009_prd_skills",
    )

    assert payload["matched_skills"]
