package npcoccurrences

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/shared"
)

type orderedOccurrenceResponse struct {
	value       occurrenceResponse
	earliest    int
	hasEvidence bool
}

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

func canonicalizeOccurrence(occurrence *occurrenceResponse, order shared.SourceRefOrder, sourceID string) (int, bool) {
	if occurrence == nil {
		return 0, false
	}
	refs := order.Canonicalize(canonicalSourceRefs(occurrence.SourceRefs, sourceID))
	occurrence.SourceRefs = occurrenceResponseRefs(refs)
	return order.EarliestValid(refs)
}

func canonicalOccurrenceList(response extractionResponse, sourceID string) dnd.NPCOccurrenceList {
	occurrences := make([]dnd.NPCOccurrence, len(response.Occurrences))
	for index, occurrence := range response.Occurrences {
		occurrences[index] = dnd.NPCOccurrence{
			NPCID:      occurrence.NPCID,
			Name:       occurrence.Name,
			Kind:       dnd.NPCOccurrenceKind(occurrence.Kind),
			SourceRefs: canonicalSourceRefs(occurrence.SourceRefs, sourceID),
		}
	}
	if response.Occurrences == nil {
		occurrences = nil
	}
	return dnd.NPCOccurrenceList{Occurrences: occurrences}
}

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

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