package backend

import (
	"fmt"
	"os/exec"
	"strings"
)

func (a *App) UpdateServiceCommon(commitId string, projectNames []string) (string, error) {
	if commitId == "" {
		return "", fmt.Errorf("commit id is empty")
	}

	if len(projectNames) == 0 {
		return "", fmt.Errorf("no projects selected")
	}

	var results strings.Builder
	results.WriteString(fmt.Sprintf("开始更新 Common 版本: %s\n", commitId))
	results.WriteString(fmt.Sprintf("共选择 %d 个项目\n\n", len(projectNames)))

	for _, projectName := range projectNames {
		var projectPath string
		found := false
		for _, project := range a.settings.Projects {
			if project.Name == projectName {
				projectPath = project.Path
				found = true
				break
			}
		}

		if !found {
			results.WriteString(fmt.Sprintf("❌ 项目 '%s' 未找到配置\n\n", projectName))
			continue
		}

		results.WriteString(fmt.Sprintf("正在更新项目: %s\n", projectName))
		results.WriteString(fmt.Sprintf("路径: %s\n", projectPath))

		if err := updateProjectCommonVersion(projectPath, commitId, &results, a.settings.ModelBasePath); err != nil {
			results.WriteString(fmt.Sprintf("❌ 更新失败: %v\n\n", err))
			continue
		}

		results.WriteString(fmt.Sprintf("✅ 更新成功\n\n"))
	}

	results.WriteString("所有项目更新完成！")
	return results.String(), nil
}

func updateProjectCommonVersion(projectPath string, commitId string, results *strings.Builder, moduleName string) error {
	goPath, err := exec.LookPath("go")
	if err != nil {
		return fmt.Errorf("Go not found: %w", err)
	}

	if moduleName == "" {
		return fmt.Errorf("Go Module Name 未配置，请在设置中填写")
	}

	results.WriteString("执行: go get -u " + moduleName + "@" + commitId + "\n")

	cmd := exec.Command(goPath, "get", "-u", fmt.Sprintf("%s@%s", moduleName, commitId))
	cmd.Dir = projectPath

	output, err := cmd.CombinedOutput()
	if err != nil {
		return fmt.Errorf("go get failed: %w\nOutput: %s", err, string(output))
	}

	results.WriteString(string(output))
	results.WriteString("\n")

	results.WriteString("执行: go mod tidy\n")

	cmd = exec.Command(goPath, "mod", "tidy")
	cmd.Dir = projectPath

	output, err = cmd.CombinedOutput()
	if err != nil {
		return fmt.Errorf("go mod tidy failed: %w\nOutput: %s", err, string(output))
	}

	results.WriteString(string(output))
	results.WriteString("\n")

	return nil
}
