#!/usr/bin/env python3
"""
Basic unit tests that exercise the protections.
"""
import unittest
from security.spoofing_protection import SpoofingProtector, SIMULATED_SHARED_SECRET
from security.hijacking_protection import HijackingProtector
from security.engineer_interface import EngineerInterface

class TestSpoofingProtector(unittest.TestCase):
    def setUp(self):
        self.prot = SpoofingProtector(secret=SIMULATED_SHARED_SECRET)

    def test_valid_hmac(self):
        payload = {"speed_mph": 120, "rpm": 6000}
        tag = SpoofingProtector.sign(payload, SIMULATED_SHARED_SECRET)
        res = self.prot.inspect_message("telemetry", "driver_device_01", payload, tag)
        self.assertTrue(res["valid"])

    def test_invalid_hmac_blocks(self):
        payload = {"speed_mph": 120}
        res = self.prot.inspect_message("telemetry", "driver_device_01", payload, "BADTAG")
        self.assertFalse(res["valid"])

    def test_crazy_speed_blocks(self):
        payload = {"speed_mph": 9999999}
        tag = SpoofingProtector.sign(payload, SIMULATED_SHARED_SECRET)
        res = self.prot.inspect_message("telemetry", "driver_device_01", payload, tag)
        self.assertFalse(res["valid"])
        self.assertEqual(res["reason"], "speed_out_of_bounds")

class TestHijackingProtector(unittest.TestCase):
    def test_soft_lockdown_on_multiple_sources(self):
        prot = HijackingProtector()
        # simulate three distinct control sources in quick succession
        prot.observe_message("control", "unknown_a", rssi=0.2)
        prot.observe_message("control", "unknown_b", rssi=0.2)
        res = prot.observe_message("control", "unknown_c", rssi=0.2)
        self.assertTrue(prot.is_soft_lockdown_active())
        self.assertEqual(res["action"], "soft_lockdown_active")

class TestEngineerInterface(unittest.TestCase):
    def test_token_issue_and_validate(self):
        token = EngineerInterface.request_engineer_token("lead_engineer")
        self.assertTrue(EngineerInterface.validate_token(token))

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