package locationregistry

import (
	"sort"

	"gitea.maximumdirect.net/eric/notarius/internal/core/source"
	"gitea.maximumdirect.net/eric/notarius/internal/modules/dnd"
	"gitea.maximumdirect.net/eric/notarius/internal/modules/dnd/locations/identity"
	"gitea.maximumdirect.net/eric/notarius/internal/modules/dnd/shared"
)

type orderedLocationResponse struct {
	value       locationResponse
	earliest    int
	hasEvidence bool
}

func canonicalizeResponse(response *extractionResponse, order shared.SourceRefOrder, sourceID string) {
	if response == nil {
		return
	}
	ordered := make([]orderedLocationResponse, len(response.Locations))
	for index := range response.Locations {
		earliest, hasEvidence := canonicalizeLocation(&response.Locations[index], order, sourceID)
		ordered[index] = orderedLocationResponse{value: response.Locations[index], earliest: earliest, hasEvidence: hasEvidence}
	}
	sort.SliceStable(ordered, func(left, right int) bool {
		if ordered[left].hasEvidence != ordered[right].hasEvidence {
			return ordered[left].hasEvidence
		}
		if !ordered[left].hasEvidence {
			return false
		}
		return ordered[left].earliest < ordered[right].earliest
	})
	for index := range ordered {
		response.Locations[index] = ordered[index].value
	}
}

func canonicalizeLocation(location *locationResponse, order shared.SourceRefOrder, sourceID string) (int, bool) {
	if location == nil {
		return 0, false
	}
	refs := order.Canonicalize(order.OrderEndpoints(canonicalSourceRefs(location.SourceRefs, sourceID)))
	location.SourceRefs = locationResponseRefs(refs)
	return order.EarliestValid(refs)
}

func canonicalLocationRegistry(response extractionResponse, sourceID string) dnd.LocationRegistry {
	if response.Locations == nil {
		return dnd.LocationRegistry{Locations: nil}
	}
	locations := make([]dnd.Location, len(response.Locations))
	for index, location := range response.Locations {
		refs := canonicalSourceRefs(location.SourceRefs, sourceID)
		locations[index] = dnd.Location{
			ID:         identity.DeriveID(location.Name, refs),
			Name:       location.Name,
			SourceRefs: refs,
		}
	}
	return dnd.LocationRegistry{Locations: locations}
}

func canonicalSourceRefs(values []locationSourceRefResponse, sourceID string) []source.SourceRef {
	if values == nil {
		return nil
	}
	refs := make([]source.SourceRef, len(values))
	for index, value := range values {
		refs[index] = source.SourceRef{SourceID: sourceID, StartUnitID: value.StartUnitID, EndUnitID: value.EndUnitID}
	}
	return refs
}

func locationResponseRefs(values []source.SourceRef) []locationSourceRefResponse {
	if values == nil {
		return nil
	}
	refs := make([]locationSourceRefResponse, len(values))
	for index, value := range values {
		refs[index] = locationSourceRefResponse{StartUnitID: value.StartUnitID, EndUnitID: value.EndUnitID}
	}
	return refs
}
