from __future__ import annotations

import argparse

import pytest

from pymulator import cli


def _args(
    *,
    attach: str | None = None,
    ecuconnect: bool = False,
    logger: bool = False,
    enet_service_broker: bool = False,
    enet_service_broker_url: str = "",
) -> argparse.Namespace:
    return argparse.Namespace(
        attach=attach,
        ecuconnect=ecuconnect,
        logger=logger,
        enet_service_broker=enet_service_broker,
        enet_service_broker_url=enet_service_broker_url,
    )


def test_ensure_optional_dependencies_requires_gs_usb_for_attach(monkeypatch: pytest.MonkeyPatch) -> None:
    from pymulator.core import can as can_module

    monkeypatch.setattr(can_module, "missing_python_can_modules", lambda _interface: ["gs_usb"])

    with pytest.raises(SystemExit, match="gs_usb"):
        cli._ensure_optional_dependencies(_args(attach="can0@500000"))


def test_ensure_optional_dependencies_requires_cancorder_utils_for_toucan_attach(
    monkeypatch: pytest.MonkeyPatch,
) -> None:
    from pymulator.core import can as can_module

    monkeypatch.setattr(can_module, "missing_python_can_modules", lambda _interface: ["cancorder-utils"])

    with pytest.raises(SystemExit, match="cancorder-utils"):
        cli._ensure_optional_dependencies(_args(attach="toucan:0@500000"))


def test_ensure_optional_dependencies_passes_when_attach_requirements_present(
    monkeypatch: pytest.MonkeyPatch,
) -> None:
    from pymulator.core import can as can_module

    monkeypatch.setattr(can_module, "missing_python_can_modules", lambda _interface: [])

    cli._ensure_optional_dependencies(_args(attach="can0@500000"))


def test_ensure_optional_dependencies_requires_zeroconf_for_enet_autodiscovery(
    monkeypatch: pytest.MonkeyPatch,
) -> None:
    monkeypatch.setattr(cli.importlib.util, "find_spec", lambda _name: None)

    with pytest.raises(SystemExit, match="zeroconf"):
        cli._ensure_optional_dependencies(_args(enet_service_broker=True, enet_service_broker_url=""))


def test_ensure_optional_dependencies_does_not_require_zeroconf_for_enet_url_override(
    monkeypatch: pytest.MonkeyPatch,
) -> None:
    monkeypatch.setattr(cli.importlib.util, "find_spec", lambda _name: None)

    cli._ensure_optional_dependencies(
        _args(
            enet_service_broker=True,
            enet_service_broker_url="https://esb.example.invalid",
        )
    )
