package placement

import (
	"crypto/sha256"
	"fmt"

	"git.frostfs.info/TrueCloudLab/frostfs-node/pkg/core/netmap"
	cid "git.frostfs.info/TrueCloudLab/frostfs-sdk-go/container/id"
	netmapSDK "git.frostfs.info/TrueCloudLab/frostfs-sdk-go/netmap"
	oid "git.frostfs.info/TrueCloudLab/frostfs-sdk-go/object/id"
)

type netMapBuilder struct {
	nmSrc          netmap.Source
	containerCache *ContainerNodesCache
}

type netMapSrc struct {
	netmap.Source

	nm *netmapSDK.NetMap
}

func NewNetworkMapBuilder(nm *netmapSDK.NetMap) Builder {
	return &netMapBuilder{
		nmSrc:          &netMapSrc{nm: nm},
		containerCache: NewContainerNodesCache(0),
	}
}

func NewNetworkMapSourceBuilder(nmSrc netmap.Source) Builder {
	return &netMapBuilder{
		nmSrc:          nmSrc,
		containerCache: NewContainerNodesCache(0),
	}
}

func (s *netMapSrc) GetNetMap(_ uint64) (*netmapSDK.NetMap, error) {
	return s.nm, nil
}

func (b *netMapBuilder) BuildPlacement(cnr cid.ID, obj *oid.ID, p netmapSDK.PlacementPolicy) ([][]netmapSDK.NodeInfo, error) {
	nm, err := netmap.GetLatestNetworkMap(b.nmSrc)
	if err != nil {
		return nil, fmt.Errorf("could not get network map: %w", err)
	}

	cn, err := b.containerCache.ContainerNodes(nm, cnr, p)
	if err != nil {
		return nil, err
	}

	return BuildObjectPlacement(nm, cn, obj)
}

func BuildObjectPlacement(nm *netmapSDK.NetMap, cnrNodes [][]netmapSDK.NodeInfo, id *oid.ID) ([][]netmapSDK.NodeInfo, error) {
	if id == nil {
		return cnrNodes, nil
	}

	binObj := make([]byte, sha256.Size)
	id.Encode(binObj)

	on, err := nm.PlacementVectors(cnrNodes, binObj)
	if err != nil {
		return nil, fmt.Errorf("could not get placement vectors for object: %w", err)
	}

	return on, nil
}

// FlattenNodes appends each row to the flat list.
func FlattenNodes(ns [][]netmapSDK.NodeInfo) []netmapSDK.NodeInfo {
	var sz int

	for i := range ns {
		sz += len(ns[i])
	}

	result := make([]netmapSDK.NodeInfo, 0, sz)

	for i := range ns {
		result = append(result, ns[i]...)
	}

	return result
}