"""
Helper utilities.
"""

import os
import pytest
import plotting_utils as plu
from plotting_utils.utils import TimerError, chunker


def test_timer_roundtrip():
    t = plu.Timer()
    t.start()
    out = t.stop()
    assert out.endswith(" s")


def test_timer_double_start_raises():
    t = plu.Timer()
    t.start()
    with pytest.raises(TimerError):
        t.start()


def test_timer_stop_without_start_raises():
    with pytest.raises(TimerError):
        plu.Timer().stop()


def test_update_params_overrides_and_adds():
    original = {"a": 1, "b": 2}
    out = plu.update_params(original, {"a": 10, "c": 3})
    assert out["a"] == 10
    assert out["b"] == 2
    assert out["c"] == 3


def test_run_command_returns_result():
    assert plu.run_command(lambda x, y=0: x + y, 2, y=3) == 5


def test_chunker_partitions_completely():
    idx = chunker(100)
    assert idx[0] == 0
    assert idx[-1] == 100
    assert all(idx[i] <= idx[i + 1] for i in range(len(idx) - 1))


def test_make_folder(tmp_path):
    cwd = os.getcwd()
    try:
        plu.make_folder(str(tmp_path), "out")
        assert (tmp_path / "out").is_dir()
    finally:
        os.chdir(cwd)


def test_make_folder_overwrite_false_keeps_contents(tmp_path):
    cwd = os.getcwd()
    try:
        plu.make_folder(str(tmp_path), "out")
        marker = tmp_path / "out" / "keep.txt"
        marker.write_text("x")
        plu.make_folder(str(tmp_path), "out", overwrite=False)
        assert marker.exists()
    finally:
        os.chdir(cwd)


def test_save_best_pdf_quality(tmp_path):
    import matplotlib.pyplot as plt
    fig, ax = plt.subplots()
    ax.plot([0, 1], [0, 1])
    plu.save_best_pdf_quality(fig, (4, 4), str(tmp_path) + os.sep, "fig.pdf", dpi=72)
    assert any(p.suffix == ".pdf" for p in tmp_path.iterdir())
    plt.close(fig)
