"""Tests for temps.command handling."""

from __future__ import annotations

import tempfile
import unittest
from pathlib import Path

from temp.commands import TempCommandError, apply_temp_command
from temp.config import TempConfig
from temp.identity import ProbeMap, load_probe_map, save_probe_map
from temp.runtime import TempRuntime


class TestTempCommands(unittest.TestCase):
    def setUp(self) -> None:
        self.tmp = tempfile.TemporaryDirectory()
        self.path = Path(self.tmp.name) / "probes.json"
        save_probe_map(self.path, ProbeMap(hot_in="28-h", tub=["28-a", "28-b", "28-c", "28-d"]))
        self.cfg = TempConfig(probe_map_path=self.path)
        self.runtime = TempRuntime(last_setup_state="ready")

    def tearDown(self) -> None:
        self.tmp.cleanup()

    def test_setup_start_clears_map(self) -> None:
        apply_temp_command(self.cfg, self.runtime, {"op": "setup_start"})
        self.assertTrue(self.runtime.setup_active)
        self.assertEqual(load_probe_map(self.path).hot_in, None)

    def test_setup_cancel_restores(self) -> None:
        apply_temp_command(self.cfg, self.runtime, {"op": "setup_start"})
        apply_temp_command(self.cfg, self.runtime, {"op": "setup_cancel"})
        self.assertFalse(self.runtime.setup_active)
        self.assertEqual(load_probe_map(self.path).hot_in, "28-h")

    def test_setup_finish_requires_ready(self) -> None:
        self.runtime.last_setup_state = "need_water"
        with self.assertRaises(TempCommandError):
            apply_temp_command(self.cfg, self.runtime, {"op": "setup_finish"})


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