package combatturns

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 orderedCombatTurnResponse struct {
	value       combatTurnResponse
	earliest    int
	hasEvidence bool
}

func canonicalizeResponse(response *extractionResponse, order shared.SourceRefOrder, sourceID string) {
	if response == nil {
		return
	}
	ordered := make([]orderedCombatTurnResponse, len(response.CombatTurns))
	for index := range response.CombatTurns {
		earliest, hasEvidence := canonicalizeCombatTurn(&response.CombatTurns[index], order, sourceID)
		ordered[index] = orderedCombatTurnResponse{
			value:       response.CombatTurns[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.CombatTurns[index] = ordered[index].value
	}
}

func canonicalizeCombatTurn(turn *combatTurnResponse, order shared.SourceRefOrder, sourceID string) (int, bool) {
	if turn == nil {
		return 0, false
	}
	refs := order.Canonicalize(order.OrderEndpoints(canonicalSourceRefs(turn.SourceRefs, sourceID)))
	turn.SourceRefs = combatResponseRefs(refs)
	return order.EarliestValid(refs)
}

func canonicalCombatTurnList(response extractionResponse, sourceID string) dnd.CombatTurnList {
	turns := make([]dnd.CombatTurn, len(response.CombatTurns))
	for index, turn := range response.CombatTurns {
		turns[index] = dnd.CombatTurn{
			Actor:      turn.Actor,
			TurnKind:   dnd.CombatTurnKind(turn.TurnKind),
			SourceRefs: canonicalSourceRefs(turn.SourceRefs, sourceID),
		}
	}
	if response.CombatTurns == nil {
		turns = nil
	}
	return dnd.CombatTurnList{CombatTurns: turns}
}

func canonicalSourceRefs(refs []combatSourceRefResponse, 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 combatResponseRefs(refs []source.SourceRef) []combatSourceRefResponse {
	if refs == nil {
		return nil
	}
	values := make([]combatSourceRefResponse, len(refs))
	for index, ref := range refs {
		values[index] = combatSourceRefResponse{StartUnitID: ref.StartUnitID, EndUnitID: ref.EndUnitID}
	}
	return values
}
