"""Performance benchmarks for piptool."""

from __future__ import annotations

from unittest.mock import Mock, patch

import pytest

from pytola.dev.piptool.cli import (
    PipToolsConfig,
    _exec_command,
    check_uv_callable,
    pip_freeze,
    pip_install,
    pip_list,
)


@pytest.mark.benchmark(group="config_initialization")
def test_config_initialization_benchmark(benchmark) -> None:
    """Benchmark configuration initialization performance."""

    def init_config():
        return PipToolsConfig()

    result = benchmark(init_config)
    assert isinstance(result, PipToolsConfig)


@pytest.mark.benchmark(group="command_execution")
def test_execute_command_benchmark(benchmark) -> None:
    """Benchmark _execute_command execution performance."""
    # Mock subprocess to avoid actual command execution
    with patch("subprocess.run") as mock_run:
        mock_run.return_value.stdout = "success"
        mock_run.return_value.stderr = ""

        def execute_command():
            _exec_command(["echo", "test"], capture_output=True)

        result = benchmark(execute_command)
        assert result is None


@pytest.mark.benchmark(group="uv_detection")
def test_check_uv_callable_benchmark(benchmark) -> None:
    """Benchmark uv callable check performance."""
    with patch("subprocess.run") as mock_run:
        mock_result = Mock()
        mock_result.returncode = 0
        mock_run.return_value = mock_result

        result = benchmark(check_uv_callable)
        assert isinstance(result, bool)


@pytest.mark.benchmark(group="pip_operations")
def test_pip_install_benchmark(benchmark) -> None:
    """Benchmark pip install operation."""
    with patch("pytola.dev.piptool.cli._exec_command"):

        def install_packages():
            pip_install(["requests", "numpy"])

        result = benchmark(install_packages)
        assert result is None


@pytest.mark.benchmark(group="pip_operations")
def test_pip_list_benchmark(benchmark) -> None:
    """Benchmark pip list operation."""
    with patch("pytola.dev.piptool.cli._exec_command") as mock_exec:
        mock_result = Mock()
        mock_result.stdout = "\n".join([f"package{i}==1.0.{i}" for i in range(100)])
        mock_exec.return_value = mock_result

        def list_packages():
            pip_list()

        result = benchmark(list_packages)
        assert result is None


@pytest.mark.benchmark(group="pip_operations")
def test_pip_freeze_benchmark(benchmark) -> None:
    """Benchmark pip freeze operation."""
    with patch("pytola.dev.piptool.cli._exec_command") as mock_exec:
        with patch("pytola.dev.piptool.cli.check_uv_callable", return_value=False):
            mock_result = Mock()
            mock_result.stdout = "\n".join([f"package{i}==1.0.{i}" for i in range(50)])
            mock_exec.return_value = mock_result

            with patch("pathlib.Path.open"):

                def freeze_packages():
                    pip_freeze()

                result = benchmark(freeze_packages)
                assert result is None


@pytest.mark.benchmark(group="concurrent_operations")
def test_multiple_pip_operations_benchmark(benchmark) -> None:
    """Benchmark multiple pip operations in sequence."""

    def run_multiple_operations():
        with patch("pytola.dev.piptool.cli._exec_command") as mock_exec:
            with patch("pytola.dev.piptool.cli.check_uv_callable", return_value=False):
                mock_result = Mock()
                mock_result.stdout = "requests==2.28.0"
                mock_exec.return_value = mock_result

                with patch("pathlib.Path.open"):
                    # Simulate typical workflow
                    pip_install(["requests"])
                    pip_list()
                    pip_freeze()

    result = benchmark(run_multiple_operations)
    assert result is None


@pytest.mark.benchmark(group="memory_usage")
def test_memory_efficiency_benchmark(benchmark) -> None:
    """Benchmark memory efficiency with large package lists."""

    def process_large_package_list():
        large_package_list = [f"package{i}" for i in range(1000)]
        with patch("pytola.dev.piptool.cli._exec_command"):
            pip_install(large_package_list)

    result = benchmark(process_large_package_list)
    assert result is None


if __name__ == "__main__":
    pytest.main([__file__, "-v", "--benchmark-only"])
