import logging

import pytest

from GramAddict.core.device_facade import create_device


def test_create_device_connection_failure(monkeypatch, caplog):
    """Test that create_device handles connection failures gracefully by logging and exiting."""

    def mock_connect_fail(device_id):
        # Simulate a uiautomator2 connection failure
        raise Exception(
            "ConnectError: [WinError 10061] No connection could be made because the target machine actively refused it"
        )

    import subprocess
    from collections import namedtuple
    from types import SimpleNamespace

    import uiautomator2 as u2

    monkeypatch.setattr(u2, "connect", mock_connect_fail)

    # Mock subprocess.run for "adb devices"
    CompletedProcess = namedtuple("CompletedProcess", ["stdout", "stderr", "returncode"])
    # Case 2: Proactive discovery with NO devices
    monkeypatch.setattr(
        subprocess,
        "run",
        lambda *args, **kwargs: SimpleNamespace(stdout="List of devices attached\n\n", returncode=0),
    )
    with pytest.raises(SystemExit):
        create_device("192.168.1.100:5555", "com.instagram.android", None)

    # Case 3: Proactive discovery with MISMATCHED IP
    monkeypatch.setattr(
        subprocess,
        "run",
        lambda *args, **kwargs: SimpleNamespace(
            stdout="List of devices attached\n10.0.0.5:5555\tdevice\n", returncode=0
        ),
    )
    with pytest.raises(SystemExit):
        create_device("192.168.1.100:5555", "com.instagram.android", None)

    def mock_adb_devices(*args, **kwargs):
        # Simulate output where the IP matches but the port is different
        return CompletedProcess(
            stdout="List of devices attached\n192.168.1.206:34771\tdevice\n", stderr="", returncode=0
        )

    monkeypatch.setattr(subprocess, "run", mock_adb_devices)

    with caplog.at_level(logging.INFO):
        with pytest.raises(SystemExit) as excinfo:
            create_device("192.168.1.206:35911", "com.instagram.android")

        assert excinfo.value.code == 1
        assert "[ADB ConnectError]" in caplog.text
        assert "🔍 Proactive Discovery" in caplog.text
        assert "192.168.1.206:34771 (MATCHING IP - Is this the same device with a different port?)" in caplog.text
