"""Tests for xnv fix module."""

from __future__ import annotations

import subprocess
from pathlib import Path
from unittest.mock import patch

import pytest

from xnv.fix import nuke_venv, create_venv, fix


@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 TestNukeVenv:
    def test_nuke_existing(self, tmp_project_with_venv: Path):
        assert (tmp_project_with_venv / "venv").exists()
        nuke_venv(tmp_project_with_venv, "venv")
        assert not (tmp_project_with_venv / "venv").exists()

    def test_nuke_nonexistent(self, tmp_project: Path):
        result = nuke_venv(tmp_project, "venv")
        assert not result


class TestCreateVenv:
    def test_create_new(self, tmp_project: Path):
        ok = create_venv(tmp_project, "venv")
        assert ok
        assert (tmp_project / "venv" / "bin" / "python").exists()
        assert (tmp_project / "venv" / "bin" / "pip").exists()


class TestFix:
    def test_fix_healthy(self, tmp_project_with_venv: Path):
        ok = fix(tmp_project_with_venv, install=False)
        assert ok

    def test_fix_broken_venv(self, tmp_project_with_venv: Path):
        # Break the venv
        python_bin = tmp_project_with_venv / "venv" / "bin" / "python"
        for p in (tmp_project_with_venv / "venv" / "bin").glob("python*"):
            p.unlink()
        python_bin.symlink_to("/nonexistent/python3.99")

        ok = fix(tmp_project_with_venv, install=False)
        assert ok
        # Venv should be recreated
        assert (tmp_project_with_venv / "venv" / "bin" / "python").exists()

    def test_fix_force_recreate(self, tmp_project_with_venv: Path):
        ok = fix(tmp_project_with_venv, force_recreate=True, install=False)
        assert ok
        assert (tmp_project_with_venv / "venv" / "bin" / "python").exists()

    def test_fix_no_venv_creates_one(self, tmp_project: Path):
        # No venv exists — fix with force should create
        ok = fix(tmp_project, force_recreate=True, install=False)
        assert ok
