from __future__ import annotations

from pathlib import Path

import aicd.tools.viz_assets as va


def test_list_bundled_not_empty() -> None:
    names = va.list_bundled_viz_files()
    assert "chart.umd.min.js" in names
    assert "mermaid.min.js" in names
    assert "vis-network.min.js" in names
    assert "vis-network.min.css" in names


def test_copy_viz_resources(tmp_path: Path) -> None:
    r = va.copy_viz_resources(tmp_path)
    assert r.get("ok") is True
    res = tmp_path / "res"
    assert res.is_dir()
    assert (res / "chart.umd.min.js").is_file()


def test_build_html_contains_res_refs() -> None:
    html = va.build_viz_html_document("t", "<p>x</p>", include_default_chart_vis_init=False)
    assert "res/mermaid.min.js" in html
    assert "res/chart.umd.min.js" in html


def test_reorder_puts_libs_before_inline_vis() -> None:
    lib = f'  <script src="res/{va.CHART_JS}"></script>\n'
    lib += f'  <script src="res/{va.MERMAID_JS}"></script>\n'
    lib += f'  <script src="res/{va.VIS_JS}"></script>\n'
    lib += '  <script>mermaid.initialize({});</script>\n'
    bad = (
        "<body><h1>x</h1>\n<script>\nconst n = new vis.DataSet([]);\n</script>\n"
        + lib
        + "</body>"
    )
    fixed = va.reorder_body_scripts_before_vis_usage(bad)
    assert fixed.index(va.VIS_JS) < fixed.index("vis.DataSet")
    same = va.reorder_body_scripts_before_vis_usage(fixed)
    assert same == fixed


def test_reorder_idempotent_on_valid_build() -> None:
    html = va.build_viz_html_document("t", "<p>x</p>", include_default_chart_vis_init=False)
    assert va.reorder_body_scripts_before_vis_usage(html) == html
