from __future__ import annotations

import json

import pytest

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


def test_default_capabilities_ios() -> None:
    device = Device(platform=Platform.IOS, name="iPhone 16 Pro", udid="SIM-1")
    caps = appium.default_capabilities(device, 8100)
    assert caps["platformName"] == "iOS"
    assert caps["appium:wdaLocalPort"] == 8100


def test_default_capabilities_android() -> None:
    device = Device(platform=Platform.ANDROID, name="emulator-5554", udid="emulator-5554")
    caps = appium.default_capabilities(device, 8200)
    assert caps["platformName"] == "Android"
    assert caps["appium:systemPort"] == 8200


def test_is_appium_ready(monkeypatch) -> None:
    class FakeResponse:
        def __enter__(self):
            return self

        def __exit__(self, exc_type, exc, tb):
            return False

        def read(self) -> bytes:
            return json.dumps({"value": {"ready": True, "build": {"version": "3.1.0"}}}).encode("utf-8")

    monkeypatch.setattr(appium, "urlopen", lambda *_args, **_kwargs: FakeResponse())
    assert appium.is_appium_ready(4723) is True
    assert appium.appium_version(4723) == "3.1.0"


def test_wait_for_appium_ready_timeout(monkeypatch) -> None:
    class FakeProc:
        def poll(self):
            return None

    monkeypatch.setattr(appium, "is_appium_ready", lambda _port: False)

    with pytest.raises(RuntimeError, match="within 0s"):
        appium.wait_for_appium_ready(4723, FakeProc(), timeout=0.0)
