"""The ``mgf-cloud-web`` CLI — argument parsing, provider resolution, dispatch."""

from __future__ import annotations

import pytest
from mgf.cloud.exceptions import ConfigError

from mgf.cloud_web import cli


def test_parser_defaults() -> None:
    args = cli.build_parser().parse_args([])
    assert args.provider == "infomaniak"
    assert args.cloud == "openstack"
    assert args.host == "127.0.0.1"
    assert args.port == 8787


def test_resolve_fake_provider() -> None:
    args = cli.build_parser().parse_args(["--provider", "fake"])
    assert cli._resolve_provider(args) is not None


_CLOUDS_YAML = """\
clouds:
  openstack:
    auth:
      auth_url: https://example.invalid/identity/v3
      username: tester
      password: secret
      project_name: proj
      project_domain_name: default
      user_domain_name: default
    region_name: dc3-a
    interface: public
    identity_api_version: 3
"""


def test_resolve_real_provider_from_clouds_yaml(tmp_path) -> None:  # type: ignore[no-untyped-def]
    """The non-fake branch resolves a provider from a clouds.yaml (lazy — no I/O)."""
    cy = tmp_path / "clouds.yaml"
    cy.write_text(_CLOUDS_YAML)
    args = cli.build_parser().parse_args(
        ["--provider", "infomaniak", "--clouds-yaml", str(cy), "--cloud", "openstack"]
    )
    provider = cli._resolve_provider(args)
    assert provider.name == "infomaniak"


def test_entrypoint_is_callable() -> None:
    from mgf.cloud_web.__main__ import main as entry

    assert callable(entry)


def test_main_serves(monkeypatch: pytest.MonkeyPatch) -> None:
    captured: dict[str, object] = {}

    def fake_serve(provider: object, host: str, port: int) -> None:
        captured.update(host=host, port=port)

    # main() does `from mgf.cloud_web.web import serve` at call time.
    monkeypatch.setattr("mgf.cloud_web.web.serve", fake_serve)
    rc = cli.main(["--provider", "fake", "--port", "9999"])
    assert rc == 0
    assert captured["port"] == 9999


def test_main_handles_cloud_error(monkeypatch: pytest.MonkeyPatch) -> None:
    def boom(_args: object) -> None:
        raise ConfigError("no credentials")

    monkeypatch.setattr(cli, "_resolve_provider", boom)
    assert cli.main(["--provider", "infomaniak"]) == 1
