"""Python virtual environment management."""

import time
import venv
from pathlib import Path

from multi_lang_build.compiler.base import BuildResult


class VenvManager:
    """Manage Python virtual environments."""

    @staticmethod
    def create(
        directory: Path,
        python_path: str | None = None,
        mirror_enabled: bool = True,
    ) -> BuildResult:
        """Create a virtual environment.

        Args:
            directory: Directory to create the venv in
            python_path: Python interpreter to use
            mirror_enabled: Whether to configure pip mirror

        Returns:
            BuildResult containing success status and output information.
        """
        start_time = time.perf_counter()

        try:
            env_builder = venv.EnvBuilder(with_pip=True, clear=True)
            env_builder.create(directory)

            # Configure pip mirror if enabled
            if mirror_enabled:
                pip_config_dir = directory / "pip.conf"
                pip_config_dir.write_text(
                    "[global]\n"
                    "index-url = https://pypi.tuna.tsinghua.edu.cn/simple\n"
                    "trusted-host = pypi.tuna.tsinghua.edu.cn\n"
                )

            duration = time.perf_counter() - start_time

            return BuildResult(
                success=True,
                return_code=0,
                stdout=f"Virtual environment created at {directory}",
                stderr="",
                output_path=directory,
                duration_seconds=duration,
            )
        except Exception as e:
            duration = time.perf_counter() - start_time
            return BuildResult(
                success=False,
                return_code=-1,
                stdout="",
                stderr=f"Failed to create virtual environment: {str(e)}",
                output_path=None,
                duration_seconds=duration,
            )
