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

package repocli

import (
	"context"
	"encoding/json"

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

func (down *Loader) Push(ctx context.Context, dir, rawref, osname, arch string) error {
	var err error

	ref, err := NewReferer(rawref)
	if err != nil {
		return err
	}
	imager, err := NewImagerFromPlace(dir)
	if err != nil {
		return err
	}
	index := imager.Index()
	for _, descr := range index.Manifests {
		digstr := descr.Digest.String()
		mime := descr.MediaType
		_, _, mandata, err := imager.ReadManifest(ctx, digstr)
		if err != nil {
			return err
		}
		man := &ocispec.Manifest{}
		err = json.Unmarshal(mandata, man)
		if err != nil {
			return err
		}
		layers := make([]ocispec.Descriptor, 0)
		layers = append(layers, man.Layers...)
		layers = append(layers, man.Config)
		for _, layer := range layers {
			digstr := layer.Digest.String()
			exists, _, err := down.cli.BlobExists(ctx, ref.RawRepo(), digstr)
			if err != nil {
				return err
			}
			if !exists {
				id, _, err := down.cli.GetUpload(ctx, ref.RawRepo())
				if err != nil {
					return err
				}
				size, reader, err := imager.LayerReader(ctx, digstr)
				if err != nil {
					return err
				}
				defer reader.Close()
				_, err = down.cli.PatchUpload(ctx, ref.RawRepo(), reader, id, size)
				if err != nil {
					return err
				}
				_, err = down.cli.PutUpload(ctx, ref.RawRepo(), nil, id, digstr, size)
				if err != nil {
					return err
				}
			}
		}
		err = down.cli.PutManifest(ctx, ref.Raw(), mandata, mime)
		if err != nil {
			return err
		}
	}
	return err
}
