"""Tests for xnv CLI."""

from __future__ import annotations

import subprocess
from pathlib import Path

import pytest

from xnv.cli import main


@pytest.fixture
def tmp_project(tmp_path: Path) -> Path:
    (tmp_path / "pyproject.toml").write_text("[project]\nname = 'test'\nversion = '0.1.0'\n")
    return tmp_path


@pytest.fixture
def tmp_project_with_venv(tmp_project: Path) -> Path:
    subprocess.run(["python3", "-m", "venv", str(tmp_project / "venv")], check=True)
    return tmp_project


class TestCLI:
    def test_doctor_healthy(self, tmp_project_with_venv: Path):
        rc = main(["doctor", str(tmp_project_with_venv)])
        assert rc == 0

    def test_doctor_no_venv(self, tmp_project: Path):
        # No venv is a warning, not an error — should still pass
        rc = main(["doctor", str(tmp_project)])
        assert rc == 0

    def test_doctor_default_no_args(self):
        # Running with no command defaults to doctor on cwd
        rc = main([])
        # Just check it doesn't crash
        assert rc in (0, 1)

    def test_create_and_nuke(self, tmp_project: Path):
        rc = main(["create", str(tmp_project)])
        assert rc == 0
        assert (tmp_project / "venv").exists()

        rc = main(["nuke", str(tmp_project)])
        assert rc == 0
        assert not (tmp_project / "venv").exists()

    def test_create_force(self, tmp_project_with_venv: Path):
        rc = main(["create", str(tmp_project_with_venv), "--force"])
        assert rc == 0

    def test_create_exists_no_force(self, tmp_project_with_venv: Path):
        rc = main(["create", str(tmp_project_with_venv)])
        assert rc == 1  # Should fail without --force

    def test_fix_no_install(self, tmp_project_with_venv: Path):
        rc = main(["fix", str(tmp_project_with_venv), "--no-install"])
        assert rc == 0

    def test_version(self, capsys):
        with pytest.raises(SystemExit) as exc:
            main(["--version"])
        assert exc.value.code == 0
