"""CLI — plan / apply / destroy against --provider fake."""

from __future__ import annotations

from typing import TYPE_CHECKING

from mgf.cloud_provision.__main__ import main

if TYPE_CHECKING:
    from pathlib import Path

    import pytest

_SPEC = 'name = "svc-cli"\nflavor = "a2-ram4-disk40"\nimage = "Ubuntu 24.04 LTS"\n'


def _spec_file(tmp_path: Path) -> str:
    f = tmp_path / "svc.toml"
    f.write_text(_SPEC)
    return str(f)


def test_plan(tmp_path: Path, capsys: pytest.CaptureFixture[str]) -> None:
    rc = main(["plan", _spec_file(tmp_path), "--provider", "fake"])
    assert rc == 0
    assert "CREATE" in capsys.readouterr().out


def test_apply_requires_yes(tmp_path: Path, capsys: pytest.CaptureFixture[str]) -> None:
    rc = main(["apply", _spec_file(tmp_path), "--provider", "fake"])
    assert rc == 0
    assert "pass --yes" in capsys.readouterr().out


def test_apply_creates(tmp_path: Path, capsys: pytest.CaptureFixture[str]) -> None:
    assert main(["apply", _spec_file(tmp_path), "--provider", "fake", "--yes"]) == 0
    assert "CREATE" in capsys.readouterr().out


def test_destroy_on_empty_cloud_is_absent(
    tmp_path: Path, capsys: pytest.CaptureFixture[str]
) -> None:
    # Each CLI run builds a fresh in-memory fake, so the cloud is empty here.
    assert main(["destroy", _spec_file(tmp_path), "--provider", "fake", "--yes"]) == 0
    assert "absent" in capsys.readouterr().out


def test_spec_error_returns_2(tmp_path: Path, capsys: pytest.CaptureFixture[str]) -> None:
    rc = main(["plan", str(tmp_path / "nope.toml"), "--provider", "fake"])
    assert rc == 2
    assert "spec error" in capsys.readouterr().err
