package main

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

	"github.com/pingcap/agent-git-service/internal/sync/gitmirror"
)

// mirrorGitRepository keeps both source and target credentials in the local
// executor process. Neither token is embedded in a remote URL or sent to AGS.
// A bare mirror preserves branches, tags, and GitHub PR head refs that the
// source advertises.
func mirrorGitRepository(ctx context.Context, sourceRemote, sourceToken, targetRemote, targetToken, workDir string) error {
	return gitmirror.MirrorRepository(ctx, sourceRemote, sourceToken, targetRemote, targetToken, workDir)
}

func runGit(ctx context.Context, dir string, args ...string) error {
	commandArgs := make([]string, 0, len(args)+2)
	if dir != "" {
		commandArgs = append(commandArgs, "-C", dir)
	}
	commandArgs = append(commandArgs, args...)
	cmd := exec.CommandContext(ctx, "git", commandArgs...)
	output, err := cmd.CombinedOutput()
	if err != nil {
		return fmt.Errorf("git %s: %w: %s", strings.Join(args, " "), err, strings.TrimSpace(string(output)))
	}
	return nil
}

func gitHTTPAuthorizationConfig(token string) []string {
	return gitmirror.GitHTTPAuthorizationConfig(token)
}

func githubGitRemote(apiURL, owner, repo string) (string, error) {
	return gitRemoteForAPIBase(apiURL, owner, repo)
}

func agsGitRemote(apiURL, owner, repo string) (string, error) {
	return gitRemoteForAPIBase(apiURL, owner, repo)
}

func gitRemoteForAPIBase(apiURL, owner, repo string) (string, error) {
	return gitmirror.RemoteForAPIBase(apiURL, owner, repo)
}
