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

import (
	"context"
	"os"
	"time"

	"github.com/dustin/go-humanize"
	"github.com/spf13/cobra"

	"mstore/pkg/auxtool"
	"mstore/pkg/auxutar"
	"mstore/pkg/gcrcli"
	"mstore/pkg/repocli"
)

// PullImage
type PullImageParams struct {
	Imagepath       string
	Filepath        string
	UseGoogleClient bool
	Arch            string
	OS              string
	Variant         string
}

type PullImageResult struct {
	Filepath string `json:"filepath"`
	Size     string `json:"size"`
}

func (util *ImageUtil) PullImage(cmd *cobra.Command, args []string) {
	util.pullImageParams.Imagepath = args[0]
	util.pullImageParams.Filepath = args[1]
	res := &PullImageResult{}
	var err error
	if util.pullImageParams.UseGoogleClient {
		res, err = util.gcrPullImage(&util.commonImageParams, &util.pullImageParams)
	} else {
		res, err = util.pullImage(&util.commonImageParams, &util.pullImageParams)
	}
	printResponse(res, err)
}

func (util *ImageUtil) pullImage(common *CommonImageParams, params *PullImageParams) (*PullImageResult, error) {
	var err error
	res := &PullImageResult{}

	timeout := time.Duration(common.Timeout) * time.Second
	ctx, _ := context.WithTimeout(context.Background(), timeout)

	ref, err := repocli.NewReferer(params.Imagepath)
	if err != nil {
		return res, err
	}
	ref.SetUserinfo(common.Username, common.Password)
	mw := repocli.NewBasicAuthMiddleware(ref.Userinfo())
	cli := repocli.NewClient(nil, mw)
	load := repocli.NewLoader(cli)

	if err != nil {
		return res, err
	}
	imageDir := auxtool.MakeTmpFilename(params.Filepath)
	err = load.Pull(ctx, ref.Raw(), imageDir, params.OS, params.Arch, params.Variant)
	if err != nil {
		return res, err
	}
	err = auxutar.Archive(imageDir, params.Filepath)
	defer os.RemoveAll(imageDir)
	if err != nil {
		return res, err
	}
	filestat, err := os.Stat(params.Filepath)
	if err != nil {
		return res, err
	}
	size := filestat.Size()
	res.Size = humanize.Comma(size)
	res.Filepath = params.Filepath

	return res, err
}

func (util *ImageUtil) gcrPullImage(common *CommonImageParams, params *PullImageParams) (*PullImageResult, error) {
	var err error
	ctx := context.Background()
	res := &PullImageResult{}

	cli := gcrcli.NewClient(common.SkipTLSVerify)
	timeout := time.Duration(common.Timeout) * time.Second

	params.Imagepath, err = packUserinfo(params.Imagepath, common.Username, common.Password)
	if err != nil {
		return res, err
	}
	ctx, _ = context.WithTimeout(ctx, timeout)
	err = cli.PullImage(ctx, params.Imagepath, params.Filepath)
	if err != nil {
		return res, err
	}
	filestat, err := os.Stat(params.Filepath)
	if err != nil {
		return res, err
	}
	size := filestat.Size()
	res.Size = humanize.Comma(size)
	res.Filepath = params.Filepath
	return res, err
}
