import struct
import asyncio
from unittest.mock import AsyncMock
from pm3py.protocol import Cmd
from pm3py.transport import PM3Response
from pm3py.hw import HWCommands

def make_ng_response(cmd: int, status: int, payload: bytes) -> PM3Response:
    return PM3Response(cmd=cmd, status=status, reason=0, ng=True, data=payload)

def make_mock_transport():
    transport = AsyncMock()
    return transport

def test_ping():
    transport = make_mock_transport()
    hw = HWCommands(transport)
    ping_data = bytes(range(32))
    transport.send_ng.return_value = make_ng_response(Cmd.PING, 0, ping_data)
    result = asyncio.get_event_loop().run_until_complete(hw.ping(32))
    assert result["success"] is True
    assert result["length"] == 32

def test_version():
    transport = make_mock_transport()
    hw = HWCommands(transport)
    # Build version response: id(4) + section_size(4) + versionstr_len(4) + versionstr
    vstr = b"Proxmark3 OS\x00"
    payload = struct.pack("<III", 0x270B0A40, 512*1024, len(vstr)) + vstr
    transport.send_ng.return_value = make_ng_response(Cmd.VERSION, 0, payload)
    result = asyncio.get_event_loop().run_until_complete(hw.version())
    assert "chip_id" in result
    assert "version_string" in result

def test_status():
    transport = make_mock_transport()
    hw = HWCommands(transport)
    transport.send_ng.return_value = make_ng_response(Cmd.STATUS, 0, b"")
    result = asyncio.get_event_loop().run_until_complete(hw.status())
    assert result["status"] == 0

def test_led():
    transport = make_mock_transport()
    hw = HWCommands(transport)
    transport.send_ng.return_value = make_ng_response(Cmd.LED_CONTROL, 0, b"")
    result = asyncio.get_event_loop().run_until_complete(hw.led(1, "on"))
    transport.send_ng.assert_called_once()
