"""Test the merge utility"""
import os
from junit2htmlreport import render, runner
from pathlib import Path
TESTS = Path(__file__).parent


def test_merge_folder(tmp_path):
    outfile = os.path.join(tmp_path, "test-merged.xml")
    outmatrix = os.path.join(tmp_path, "matrix.html")
    runner.run(["--merge", outfile, str(TESTS)])
    runner.run(["--theme", "dark", outfile])
    assert os.path.exists(f"{outfile}.html")

    tests = list([str(x) for x in TESTS.glob("*.xml")])
    runner.run(["--report-matrix", outmatrix] + tests)
    assert os.path.exists(outmatrix)


def test_report_matrix_theme_dir_applies_to_individual_reports(tmp_path, monkeypatch):
    monkeypatch.setattr(runner, "loader_factory", render.LoaderFactory())
    theme_dir = tmp_path / "theme"
    theme_dir.mkdir()
    (theme_dir / "base.html").write_text(
        """
<!DOCTYPE html>
<html>
<body>
    <span>custom theme marker</span>
    {% block content %}{% endblock %}
</body>
</html>
""".strip(),
        encoding="utf-8",
    )
    (theme_dir / "report.html").write_text(
        """
{% extends "base.html" %}
{% block content %}
custom report marker
{% endblock %}
""".strip(),
        encoding="utf-8",
    )
    (theme_dir / "matrix.html").write_text(
        """
{% extends "base.html" %}
{% block content %}
custom matrix marker
{% endblock %}
""".strip(),
        encoding="utf-8",
    )
    (theme_dir / "styles.css").write_text("", encoding="utf-8")

    outmatrix = tmp_path / "matrix.html"
    report = TESTS / "junit-simple_suite.xml"

    runner.run(["--theme-dir", str(theme_dir), "--report-matrix", str(outmatrix), str(report)])
    report_html = tmp_path / "junit-simple_suite.xml.html"

    matrix_content = outmatrix.read_text(encoding="utf-8")
    report_content = report_html.read_text(encoding="utf-8")

    assert "custom matrix marker" in matrix_content
    assert "custom report marker" in report_content

    assert "custom theme marker" in matrix_content
    assert "custom theme marker" in report_content
