from __future__ import annotations

from autosana_cli import devices
from autosana_cli.models import Device, Platform


IOS_JSON = """
{
  "devices": {
    "com.apple.CoreSimulator.SimRuntime.iOS-18-0": [
      {
        "name": "iPhone 16 Pro",
        "udid": "SIM-1",
        "state": "Shutdown",
        "isAvailable": true
      }
    ],
    "com.apple.CoreSimulator.SimRuntime.iOS-17-5": [
      {
        "name": "iPhone 15",
        "udid": "SIM-2",
        "state": "Booted",
        "isAvailable": true
      }
    ]
  }
}
"""


def test_parse_ios_devices() -> None:
    parsed = devices.parse_ios_devices(IOS_JSON)
    assert [device.udid for device in parsed] == ["SIM-1", "SIM-2"]
    assert parsed[1].booted is True


def test_parse_adb_devices() -> None:
    payload = "List of devices attached\nemulator-5554\tdevice\nZX1G22\tunauthorized\n"
    assert devices.parse_adb_devices(payload) == ["emulator-5554"]


def test_resolve_ios_uses_booted_device(monkeypatch) -> None:
    booted = Device(platform=Platform.IOS, name="iPhone 15", udid="SIM-2", booted=True, runtime="iOS-17-5")
    monkeypatch.setattr(devices, "list_booted_ios_simulators", lambda: [booted])
    resolved = devices.resolve_ios_device()
    assert resolved == booted


def test_resolve_ios_boots_best_available(monkeypatch) -> None:
    available = [
        Device(platform=Platform.IOS, name="iPhone 15", udid="SIM-1", booted=False, runtime="iOS-17-5"),
        Device(platform=Platform.IOS, name="iPhone 16 Pro", udid="SIM-2", booted=False, runtime="iOS-18-0"),
    ]
    monkeypatch.setattr(devices, "list_booted_ios_simulators", lambda: [])
    monkeypatch.setattr(devices, "list_available_ios_simulators", lambda: available)
    monkeypatch.setattr(devices, "boot_ios_simulator", lambda device: Device(**{**device.__dict__, "booted": True}))

    resolved = devices.resolve_ios_device(auto_boot=True)

    assert resolved.udid == "SIM-2"
    assert resolved.booted is True


def test_resolve_ios_no_boot_returns_none(monkeypatch) -> None:
    monkeypatch.setattr(devices, "list_booted_ios_simulators", lambda: [])
    resolved = devices.resolve_ios_device(auto_boot=False)
    assert resolved is None
