/*
 * Copyright 2026 Oleg Borodin <onborodin@gmail.com>
 *
 * This work is published and licensed under a Creative Commons
 * Attribution-NonCommercial-NoDerivatives 4.0 International License.
 *
 * Distribution of this work is permitted, but commercial use and
 * modifications are strictly prohibited.
 */
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{},
	}
	params.Imagepath, err = packUserinfo(params.Imagepath, common.Username, common.Password)
	if err != nil {
		return res, err
	}
	timeout := time.Duration(common.Timeout) * time.Second
	ctx, _ := context.WithTimeout(context.Background(), timeout)
	ref, err := repocli.ParseReference(params.Imagepath)
	if err != nil {
		return res, err
	}
	mw := repocli.NewBasicAuthMiddleware(ref.Userinfo())
	cli := repocli.NewClient(nil, mw)
	exists, mime, man, err := cli.GetRawManifest(ctx, ref.Repo())
	if !exists {
		err = fmt.Errorf("Manifest not found")
		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
}
