# Copyright 2026 Espressif Systems (Shanghai) Co., Ltd.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import math
import unittest

from esp_viewer.core.mock_device import MockDevice


class TestSignalSimulation(unittest.TestCase):
    def test_mock_type_switching(self):
        # Setup Mock with Waveform profile
        profile = {
            "meta": {"mock_type": "waveform"},
            "streams": [{"id": "s1", "type": "data", "fields": ["ts", "val"]}],
        }
        mock = MockDevice(profile=profile)
        mock.streaming = True
        mock.running = True

        # Verify it uses _gen_waveform (indirectly by checking if it emits)
        # Note: Simulation runs in a thread, so we test the logic helpers if possible
        # or just verify params are accessible.
        mock.params["carrier_freq"] = 10.0
        self.assertEqual(mock.params["carrier_freq"], 10.0)

    def test_imu_trigger_logic(self):
        # Setup Mock with IMU profile
        profile = {
            "meta": {"mock_type": "imu"},
            "streams": [
                {"id": "imu", "type": "data", "fields": ["ts", "ax", "ay", "az"]}
            ],
        }
        mock = MockDevice(profile=profile)
        mock.t = 1.0
        mock.params["shake_threshold"] = 1.0  # Low threshold

        # Test the trigger logic explicitly by calling the math
        # Shake detection: mag > threshold
        accel = [1.0, 1.0, 1.0]  # mag = sqrt(3) ~= 1.73
        mag = math.sqrt(sum(a * a for a in accel))
        self.assertTrue(mag > 1.0)

    def test_waveform_logic(self):
        mock = MockDevice()
        mock.t = 0.5
        mock.params["carrier_freq"] = 2.0
        mock.params["carrier_amp"] = 100.0

        # Verify math
        phase = 2 * math.pi * 2.0 * 0.5
        val = 100.0 * math.sin(phase)
        self.assertAlmostEqual(val, 0.0, places=5)


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