"""Go module building utilities."""

from pathlib import Path

from loguru import logger

from multi_lang_build.compiler.base import BuildResult


class GoModuleBuilder:
    """Build all packages in a Go module."""

    @staticmethod
    def build_all(
        go_executable: str,
        source_dir: Path,
        output_dir: Path,
        env: dict[str, str],
        platform: str | None,
        run_build,
        stream_output: bool = True,
    ) -> BuildResult:
        """Build all packages in the module.

        Args:
            go_executable: Path to Go executable
            source_dir: Source directory
            output_dir: Output directory for binaries
            env: Environment variables
            platform: Target platform (e.g., "linux/amd64")
            run_build: Callback to execute build
            stream_output: Whether to stream output

        Returns:
            BuildResult with success status
        """
        build_args = [go_executable, "build", "-o", str(output_dir), "./..."]

        env_copy = env.copy()
        if platform:
            env_copy["GOOS"], env_copy["GOARCH"] = platform.split("/")

        logger.info("🔨 开始构建...")
        logger.info(f"构建命令: {' '.join(build_args)}")
        build_result = run_build(build_args, source_dir, output_dir, env_copy)

        if build_result["success"]:
            logger.info("✅ 构建成功")

        return build_result

    @staticmethod
    def tidy(
        go_executable: str,
        source_dir: Path,
        env: dict[str, str],
        run_build,
        stream_output: bool = True,
    ) -> BuildResult:
        """Run go mod tidy to clean up dependencies.

        Args:
            go_executable: Path to Go executable
            source_dir: Source directory
            env: Environment variables
            run_build: Callback to execute build
            stream_output: Whether to stream output

        Returns:
            BuildResult with success status
        """
        tidy_cmd = [go_executable, "mod", "tidy"]
        logger.info("📦 执行 go mod tidy...")
        logger.info(f"构建命令: {' '.join(tidy_cmd)}")
        tidy_result = run_build(tidy_cmd, source_dir, source_dir, env)

        if tidy_result["success"]:
            logger.info("✅ 依赖整理完成")

        return tidy_result
