import io
import sys
from contextlib import redirect_stdout
from pathlib import Path
import tempfile
import unittest

ROOT = Path(__file__).resolve().parents[1]
SRC = ROOT / "src"

if str(SRC) not in sys.path:
    sys.path.insert(0, str(SRC))

from bpm_finder.cli import main  # noqa: E402
from test_api import write_click_track  # noqa: E402


class CliTests(unittest.TestCase):
    def test_analyze_audio_command_outputs_bpm(self) -> None:
        with tempfile.TemporaryDirectory() as temp_dir:
            wav_path = Path(temp_dir) / "click-track.wav"
            write_click_track(wav_path, bpm=120.0)

            buffer = io.StringIO()
            with redirect_stdout(buffer):
                exit_code = main(["analyze-audio", str(wav_path)])

        self.assertEqual(exit_code, 0)
        self.assertAlmostEqual(float(buffer.getvalue().strip()), 120.0, delta=1.0)

    def test_tap_command_outputs_bpm(self) -> None:
        buffer = io.StringIO()
        with redirect_stdout(buffer):
            exit_code = main(["tap", "--intervals", "500,500,500,500"])

        self.assertEqual(exit_code, 0)
        self.assertEqual(buffer.getvalue().strip(), "120.0")

    def test_bpm_to_ms_command_outputs_duration(self) -> None:
        buffer = io.StringIO()
        with redirect_stdout(buffer):
            exit_code = main(["bpm-to-ms", "--bpm", "128", "--division", "4"])

        self.assertEqual(exit_code, 0)
        self.assertEqual(buffer.getvalue().strip(), "468.75")


if __name__ == "__main__":
    unittest.main()
