// Package invariants validates normalized D&D location occurrence artifacts.
package invariants

import (
	"context"
	"fmt"
	"sort"
	"strconv"
	"strings"

	"gitea.maximumdirect.net/eric/notarius/internal/core/source"
	"gitea.maximumdirect.net/eric/notarius/internal/framework/contracts"
	"gitea.maximumdirect.net/eric/notarius/internal/framework/pipeline"
	"gitea.maximumdirect.net/eric/notarius/internal/modules/dnd"
	"gitea.maximumdirect.net/eric/notarius/internal/modules/dnd/shared"
	"gitea.maximumdirect.net/eric/notarius/internal/modules/dnd/shared/diagnostics"
	occurrenceshape "gitea.maximumdirect.net/eric/notarius/internal/modules/dnd/validate/locationoccurrences/shape"
)

const (
	Key        = "normalize/dnd/location-occurrences/invariants"
	ReasonCode = "invalid_location_occurrence_normalization"
	policy     = "dnd.location_occurrences.validator.normalized.v1"
)

type Options struct{}
type Validator struct{}

var _ contracts.TypedValidator[dnd.LocationOccurrenceList] = (*Validator)(nil)
var _ pipeline.CheckpointFingerprintProvider = (*Validator)(nil)

func New(Options) *Validator      { return &Validator{} }
func (v *Validator) Name() string { return Key }
func (v *Validator) ExecutionClass() contracts.ExecutionClass {
	return contracts.ExecutionClassDeterministic
}
func (v *Validator) CheckpointFingerprints() []pipeline.CheckpointFingerprint {
	return []pipeline.CheckpointFingerprint{{Name: "policy", Value: policy}}
}

func (v *Validator) Validate(_ context.Context, req contracts.TypedValidationRequest[dnd.LocationOccurrenceList]) (contracts.ValidationResult, error) {
	if occurrenceshape.Validate(req.Value) != nil {
		return contracts.ValidationResult{Approved: true}, nil
	}
	index := source.NewDocumentIndex(req.Source)
	if !allSourceRefsValid(index, req.Value) {
		return contracts.ValidationResult{Approved: true}, nil
	}
	issues := issuesFor(shared.NewSourceRefOrderFromIndex(index), req.Value)
	if len(issues) == 0 {
		return contracts.ValidationResult{Approved: true}, nil
	}
	return contracts.ValidationResult{Approved: false, ReasonCode: ReasonCode, Message: diagnostics.Aggregate("invalid location occurrence normalization", issues), CorrectionGuidance: "Return location occurrences in canonical transcript order, without duplicates, using consistent proper location names and supported occurrence kinds."}, nil
}

func allSourceRefsValid(index source.DocumentIndex, value dnd.LocationOccurrenceList) bool {
	for _, occurrence := range value.Occurrences {
		for _, ref := range occurrence.SourceRefs {
			if index.ValidateRef(ref) != nil {
				return false
			}
		}
	}
	return true
}

func issuesFor(order shared.SourceRefOrder, value dnd.LocationOccurrenceList) []string {
	issues := make([]string, 0)
	for index, occurrence := range value.Occurrences {
		prefix := fmt.Sprintf("occurrences[%d]", index)
		for refIndex := 1; refIndex < len(occurrence.SourceRefs); refIndex++ {
			previous, current := occurrence.SourceRefs[refIndex-1], occurrence.SourceRefs[refIndex]
			if order.Less(current, previous) {
				issues = append(issues, fmt.Sprintf("%s.source_refs are not in canonical order at index %d", prefix, refIndex))
			} else if current == previous {
				issues = append(issues, fmt.Sprintf("%s.source_refs[%d] duplicates the previous reference", prefix, refIndex))
			}
		}
	}
	if !sort.SliceIsSorted(value.Occurrences, func(left, right int) bool {
		return lessOccurrence(order, value.Occurrences[left], value.Occurrences[right])
	}) {
		issues = append(issues, "occurrences are not in canonical order")
	}
	seen := make(map[string]int)
	for index, occurrence := range value.Occurrences {
		key := exactIdentity(occurrence)
		if previous, ok := seen[key]; ok {
			issues = append(issues, fmt.Sprintf("occurrences[%d] duplicates occurrence %d", index, previous))
			continue
		}
		seen[key] = index
	}
	return issues
}

func lessOccurrence(order shared.SourceRefOrder, left, right dnd.LocationOccurrence) bool {
	leftPosition, leftHasEvidence := order.EarliestValid(left.SourceRefs)
	rightPosition, rightHasEvidence := order.EarliestValid(right.SourceRefs)
	if leftHasEvidence != rightHasEvidence {
		return leftHasEvidence
	}
	if leftHasEvidence && leftPosition != rightPosition {
		return leftPosition < rightPosition
	}
	if left.LocationID != right.LocationID {
		return left.LocationID < right.LocationID
	}
	if left.Name != right.Name {
		return left.Name < right.Name
	}
	if kindOrder(left.Kind) != kindOrder(right.Kind) {
		return kindOrder(left.Kind) < kindOrder(right.Kind)
	}
	if left.Kind != right.Kind {
		return left.Kind < right.Kind
	}
	return sourceRefsLess(order, left.SourceRefs, right.SourceRefs)
}
func kindOrder(kind dnd.LocationOccurrenceKind) int {
	switch kind {
	case dnd.LocationOccurrenceKindVisited:
		return 0
	case dnd.LocationOccurrenceKindPlanned:
		return 1
	case dnd.LocationOccurrenceKindRecalled:
		return 2
	case dnd.LocationOccurrenceKindMentioned:
		return 3
	default:
		return 4
	}
}
func sourceRefsLess(order shared.SourceRefOrder, left, right []source.SourceRef) bool {
	for index := 0; index < len(left) && index < len(right); index++ {
		if left[index] != right[index] {
			return order.Less(left[index], right[index])
		}
	}
	return len(left) < len(right)
}
func exactIdentity(occurrence dnd.LocationOccurrence) string {
	var key strings.Builder
	writeKeyString(&key, occurrence.LocationID)
	writeKeyString(&key, occurrence.Name)
	writeKeyString(&key, string(occurrence.Kind))
	for _, ref := range occurrence.SourceRefs {
		writeKeyString(&key, ref.SourceID)
		writeKeyInt(&key, ref.StartUnitID)
		writeKeyInt(&key, ref.EndUnitID)
	}
	return key.String()
}
func writeKeyString(builder *strings.Builder, value string) {
	builder.WriteString(strconv.Itoa(len(value)))
	builder.WriteByte(':')
	builder.WriteString(value)
}
func writeKeyInt(builder *strings.Builder, value int) {
	builder.WriteString(strconv.Itoa(value))
	builder.WriteByte(';')
}

func Spec() pipeline.ValidatorSpec {
	return pipeline.ValidatorSpec{Key: Key, ExecutionClass: contracts.ExecutionClassDeterministic}
}
func Register(registry *pipeline.ValidatorRegistry) error {
	return pipeline.RegisterTypedValidatorBuilder(registry, dnd.LocationOccurrenceListKind, Spec(), validateOptions, func(request pipeline.BuildRequest) (contracts.TypedValidator[dnd.LocationOccurrenceList], error) {
		options, err := DecodeOptions(request.Options)
		if err != nil {
			return nil, err
		}
		return New(options), nil
	})
}
func DecodeOptions(options map[string]any) (Options, error) {
	if err := pipeline.RejectUnknownOptions(options); err != nil {
		return Options{}, err
	}
	return Options{}, nil
}
func validateOptions(options map[string]any) error { _, err := DecodeOptions(options); return err }
