from types import SimpleNamespace

from src.utils import ino


def _ports(mocker, devices):
    mocker.patch.object(ino.list_ports, 'comports', return_value=[
        SimpleNamespace(device=name, vid=vid, description='Serielles USB-Geraet',
                        manufacturer='Microsoft', product=None)
        for name, vid in devices
    ])


def test_stale_configured_port_falls_back_to_detection(mocker, monkeypatch):
    # Nach dem Flashen wechselt der 32u4 die Nummer: COM3 -> COM5.
    monkeypatch.setenv(ino.ARDUINO_PORT_ENV, 'COM3')
    _ports(mocker, [('COM5', 0x2341)])

    assert ino.getArduinoPort() == 'COM5'


def test_configured_port_wins_when_present(mocker, monkeypatch):
    monkeypatch.setenv(ino.ARDUINO_PORT_ENV, 'COM7')
    _ports(mocker, [('COM5', 0x2341), ('COM7', 0x2341)])

    assert ino.getArduinoPort() == 'COM7'


def test_detects_board_by_vendor_id(mocker, monkeypatch):
    monkeypatch.delenv(ino.ARDUINO_PORT_ENV, raising=False)
    _ports(mocker, [('COM1', 0x1234), ('COM5', 0x2341)])

    assert ino.detectArduinoPort() == 'COM5'


def test_returns_none_without_board(mocker, monkeypatch):
    monkeypatch.delenv(ino.ARDUINO_PORT_ENV, raising=False)
    _ports(mocker, [('COM1', 0x1234)])

    assert ino.getArduinoPort() is None


def test_write_hex_gets_generous_timeout():
    # Firmware tippt menschlich langsam: 12 Zeichen brauchen mehrere Sekunden.
    password = 'geheim123456'
    command = 'writeHex,' + password.encode('utf-8').hex()

    assert ino._responseTimeout(command) >= 12

def test_short_commands_stay_snappy():
    assert ino._responseTimeout('health') == 2
    assert ino._responseTimeout('press,32') == 2
