"""Go environment preparation utilities."""

import os
from pathlib import Path

from loguru import logger


class GoEnvironment:
    """Prepare Go build environment with cache paths."""

    @staticmethod
    def prepare(environment: dict[str, str] | None = None) -> dict[str, str]:
        """Prepare environment with GOMODCACHE and GOCACHE set.

        Args:
            environment: Base environment variables

        Returns:
            Environment with cache paths set
        """
        env = environment.copy() if environment else {}

        # Set HOME if not present (needed for Path.home() and GOCACHE)
        if "HOME" not in env:
            home = os.environ.get("HOME") or "/root"
            env["HOME"] = home

        # Set GOMODCACHE if not present
        if "GOMODCACHE" not in env and "GOPATH" not in env:
            default_cache = Path(env["HOME"]) / "go" / "pkg" / "mod"
            env["GOMODCACHE"] = str(default_cache)
            logger.info(f"Go模块缓存: {default_cache}")

        # Set GOCACHE if not present
        if "GOCACHE" not in env:
            cache_dir = Path(env["HOME"]) / ".cache" / "go-build"
            env["GOCACHE"] = str(cache_dir)
            logger.info(f"Go构建缓存: {cache_dir}")

        return env
