/*
 * Copyright 2026 Oleg Borodin <onborodin@gmail.com>
 */
package imagecmd

import (
	"net/url"
	"path"
	"runtime"
	"strings"

	"github.com/spf13/cobra"
	"github.com/spf13/viper"
)

type ImageUtil struct {
	imageManifestParams ImageManifestParams
	imageTagsParams     ImageTagsParams
	catalogImagesParams CatalogImagesParams
	pullImageParams     PullImageParams
	pushImageParams     PushImageParams
	deleteImageParams   DeleteImageParams
	checkImagesParams   CheckImagesParams
	commonImageParams   CommonImageParams
}

func NewImageUtil() *ImageUtil {
	return &ImageUtil{}
}

func (util *ImageUtil) CreateImageCmds() *cobra.Command {
	const defaultTimeout uint64 = 30 // Second

	var subCmd = &cobra.Command{
		Use:     "images",
		Short:   "Image operations",
		Aliases: []string{"image"},
	}
	subCmd.PersistentFlags().StringVarP(&util.commonImageParams.Username, "user", "u", "", "Username")
	subCmd.PersistentFlags().StringVarP(&util.commonImageParams.Password, "pass", "p", "", "Password")
	subCmd.PersistentFlags().Uint64VarP(&util.commonImageParams.Timeout, "timeout", "t", defaultTimeout, "Operation timeout")
	subCmd.PersistentFlags().BoolVarP(&util.commonImageParams.SkipTLSVerify, "skipVerify", "S", true, "Skip server certificate verify")
	subCmd.MarkFlagsRequiredTogether("user", "pass")

	vi := viper.New()
	vi.SetEnvPrefix("mstore")
	vi.BindEnv("user")
	vi.BindEnv("pass")
	util.commonImageParams.Username = vi.GetString("user")
	util.commonImageParams.Password = vi.GetString("pass")

	// PushImage
	var pushImageCmd = &cobra.Command{
		Use:   "push filename [user:pass@]hostname[:port]/path:tag",
		Short: "Push container image from local tar file into registry",
		Args:  cobra.ExactArgs(2),
		Run:   util.PushImage,
	}
	subCmd.AddCommand(pushImageCmd)

	// PullImage
	var pullImageCmd = &cobra.Command{
		Use:   "pull [user:pass@]hostname[:port]/path:tag filename",
		Short: "Pull container image from registry into local file",
		Args:  cobra.ExactArgs(2),
		Run:   util.PullImage,
	}
	pullImageCmd.Flags().BoolVarP(&util.pullImageParams.UseGoogleClient, "google", "G", false, "Use google client")
	pullImageCmd.Flags().StringVarP(&util.pullImageParams.OS, "os", "O", runtime.GOOS, "Get operation system type")
	pullImageCmd.Flags().StringVarP(&util.pullImageParams.Arch, "arch", "A", runtime.GOARCH, "Get CPU architerure")
	pullImageCmd.Flags().StringVarP(&util.pullImageParams.Variant, "variant", "V", "", "Get OS or CPU variant")

	subCmd.AddCommand(pullImageCmd)

	// DeleteImage
	var deleteImageCmd = &cobra.Command{
		Use:   "delete [user:pass@]hostname[:port]/path:tag",
		Short: "Delete container image from registry",
		Args:  cobra.ExactArgs(1),
		Run:   util.DeleteImage,
	}
	subCmd.AddCommand(deleteImageCmd)

	// ImageManifest
	var imageManifestCmd = &cobra.Command{
		Use:   "manifest [user:pass@]hostname[:port]/path:tag",
		Short: "Show container image manifest info",
		Args:  cobra.ExactArgs(1),
		Run:   util.ImageManifest,
	}
	subCmd.AddCommand(imageManifestCmd)

	// Imagetags
	var imageTagsCmd = &cobra.Command{
		Use:   "tags [user:pass@]hostname[:port]/path:tag",
		Short: "List container tags",
		Args:  cobra.ExactArgs(1),
		Run:   util.ImageTags,
	}
	subCmd.AddCommand(imageTagsCmd)

	// CatalogImages
	var catalogImagesCmd = &cobra.Command{
		Use:   "catalog [user:pass@]hostname[:port]",
		Short: "List image repositories",
		Args:  cobra.ExactArgs(1),
		Run:   util.CatalogImages,
	}
	subCmd.AddCommand(catalogImagesCmd)

	// CheckFiles
	var checkImagesCmd = &cobra.Command{
		Use:   "check [user:pass@]hostname[:port][/path:tag]",
		Short: "Check containet image",
		Args:  cobra.ExactArgs(1),
		Run:   util.CheckImages,
	}
	subCmd.AddCommand(checkImagesCmd)

	return subCmd
}

type CommonImageParams struct {
	Timeout       uint64
	Username      string
	Password      string
	SkipTLSVerify bool
}

func packUserinfo(resurseuri, username, password string) (string, error) {
	var err error
	var res string
	if !strings.Contains(resurseuri, "://") {
		resurseuri = "https://" + resurseuri
	}
	uri, err := url.Parse(resurseuri)
	if err != nil {
		return res, err
	}
	uri.Path = path.Clean(uri.Path)
	if username != "" && password != "" {
		uri.User = url.UserPassword(username, password)
	}
	res = uri.String()
	return res, err
}
