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

import (
	"context"
	"encoding/json"
	"fmt"
	"time"

	ocispec "github.com/opencontainers/image-spec/specs-go/v1"
	"github.com/spf13/cobra"

	"mstore/pkg/repocli"
)

// ImageManifest
type ImageManifestParams struct {
	Imagepath string
}

type ImageManifestResult struct {
	Index    *ocispec.Index    `json:"index,omitempty"`
	Manifest *ocispec.Manifest `json:"manifest,omitempty"`
}

func (util *ImageUtil) ImageManifest(cmd *cobra.Command, args []string) {
	util.imageManifestParams.Imagepath = args[0]
	res, err := util.imageManifest(&util.commonImageParams, &util.imageManifestParams)
	printResponse(res, err)
}

func (util *ImageUtil) imageManifest(common *CommonImageParams, params *ImageManifestParams) (*ImageManifestResult, error) {
	var err error
	res := &ImageManifestResult{
		Index:    &ocispec.Index{},
		Manifest: &ocispec.Manifest{},
	}
	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)
	accepts := []string{
		repocli.MediaTypeDDMLv2,
		repocli.MediaTypeDDMv2,
		repocli.MediaTypeOIMv1,
		repocli.MediaTypeOIIv1,
	}
	_, mime, man, _, err := cli.GetRawManifest(ctx, ref.Raw(), accepts)
	if err != nil {
		return res, err
	}
	switch mime {
	case repocli.MediaTypeDDMLv2, repocli.MediaTypeOIIv1:
		err = json.Unmarshal(man, res.Index)
		if err != nil {
			return res, err
		}
	case repocli.MediaTypeDDMv2, repocli.MediaTypeOIMv1:
		err = json.Unmarshal(man, res.Manifest)
		if err != nil {
			return res, err
		}
	default:
		err = fmt.Errorf("Unknown content type: %s", mime)
		return res, err
	}
	return res, err
}
