package cmd

import (
	"fmt"

	gogitea "code.gitea.io/sdk/gitea"
	"github.com/spf13/cobra"
)

var cloneCmd = &cobra.Command{
	Use:   "clone <repo>",
	Short: "Clone a Gitea repo (use owner/repo or just repo for your own)",
	Args:  cobra.ExactArgs(1),
	RunE: func(cmd *cobra.Command, args []string) error {
		cfg, err := loadConfig()
		if err != nil {
			return err
		}

		owner, repoName := parseOwnerRepo(args[0], cfg.Username)

		client, err := gogitea.NewClient(cfg.URL, gogitea.SetToken(cfg.Token))
		if err != nil {
			return fmt.Errorf("connecting to Gitea: %w", err)
		}

		repo, _, err := client.GetRepo(owner, repoName)
		if err != nil {
			return fmt.Errorf("repo %s/%s not found: %w", owner, repoName, err)
		}

		cloneURL := authCloneURL(cfg, repo.CloneURL)
		fmt.Printf("Cloning %s/%s...\n", owner, repoName)
		return runGit(".", "clone", cloneURL, repoName)
	},
}

// parseOwnerRepo splits "owner/repo" or defaults owner to the current user.
func parseOwnerRepo(arg, defaultOwner string) (string, string) {
	for i, c := range arg {
		if c == '/' {
			return arg[:i], arg[i+1:]
		}
	}
	return defaultOwner, arg
}

func init() {
	rootCmd.AddCommand(cloneCmd)
}
