// Package invariants validates normalized D&D item-occurrence artifacts.
package invariants

import (
	"context"
	"fmt"

	"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"
	itemoccurrencemodel "gitea.maximumdirect.net/eric/notarius/internal/modules/dnd/itemoccurrences"
	"gitea.maximumdirect.net/eric/notarius/internal/modules/dnd/shared"
	"gitea.maximumdirect.net/eric/notarius/internal/modules/dnd/shared/diagnostics"
	itemoccurrenceshape "gitea.maximumdirect.net/eric/notarius/internal/modules/dnd/validate/itemoccurrences/shape"
)

const (
	Key        = "normalize/dnd/item-occurrences/invariants"
	ReasonCode = "invalid_normalized_item_occurrence_invariants"
	policy     = "dnd.item_occurrences.normalize_invariants.v1"
)

type Options struct{}
type Validator struct{}

var _ contracts.TypedValidator[dnd.ItemOccurrenceList] = (*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.ItemOccurrenceList]) (contracts.ValidationResult, error) {
	if err := Validate(req.Source, req.Value); err != nil {
		return contracts.ValidationResult{Approved: false, ReasonCode: ReasonCode, Message: err.Error(), CorrectionGuidance: "Return item occurrences in canonical transcript order, without duplicate occurrences, using consistent contextual item names and valid event transitions."}, nil
	}
	return contracts.ValidationResult{Approved: true}, nil
}

// Validate checks only invariants introduced by item-occurrence normalization.
// Shape and source-reference failures remain owned by their earlier validators.
func Validate(doc *source.SourceDocument, value dnd.ItemOccurrenceList) error {
	if itemoccurrenceshape.Validate(value) != nil {
		return nil
	}
	index := source.NewDocumentIndex(doc)
	if !sourceRefsValid(index, value) {
		return nil
	}
	issues := issuesFor(shared.NewSourceRefOrderFromIndex(index), value)
	if len(issues) == 0 {
		return nil
	}
	return fmt.Errorf("%s", diagnostics.Aggregate("invalid normalized item occurrence invariants", issues))
}

func issuesFor(order shared.SourceRefOrder, value dnd.ItemOccurrenceList) []string {
	issues := make([]string, 0)
	canonicalEvidence := make([]bool, len(value.Occurrences))
	seenIdentity := make(map[string][]int)
	for occurrenceIndex, occurrence := range value.Occurrences {
		prefix := fmt.Sprintf("occurrences[%d]", occurrenceIndex)
		canonicalEvidence[occurrenceIndex] = true
		if occurrence.Name != itemoccurrencemodel.DisplayValue(occurrence.Name) {
			issues = append(issues, prefix+".name is not display-normalized")
		}
		if occurrence.From != itemoccurrencemodel.DisplayValue(occurrence.From) {
			issues = append(issues, prefix+".from is not display-normalized")
		}
		if occurrence.To != itemoccurrencemodel.DisplayValue(occurrence.To) {
			issues = append(issues, prefix+".to is not display-normalized")
		}
		for refIndex := 1; refIndex < len(occurrence.SourceRefs); refIndex++ {
			previous := occurrence.SourceRefs[refIndex-1]
			current := 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))
				canonicalEvidence[occurrenceIndex] = false
			} else if current == previous {
				issues = append(issues, fmt.Sprintf("%s.source_refs[%d] duplicates the previous reference", prefix, refIndex))
				canonicalEvidence[occurrenceIndex] = false
			}
		}
		if canonicalEvidence[occurrenceIndex] {
			key := itemoccurrencemodel.CanonicalExactIdentity(occurrence)
			for _, previous := range seenIdentity[key] {
				if itemoccurrencemodel.CanonicalExactEqual(value.Occurrences[previous], occurrence) {
					issues = append(issues, fmt.Sprintf("%s duplicates item occurrence %d under normalized identity", prefix, previous))
					break
				}
			}
			seenIdentity[key] = append(seenIdentity[key], occurrenceIndex)
		}
	}
	for occurrenceIndex := 1; occurrenceIndex < len(value.Occurrences); occurrenceIndex++ {
		less := itemoccurrencemodel.Less
		if canonicalEvidence[occurrenceIndex] && canonicalEvidence[occurrenceIndex-1] {
			less = itemoccurrencemodel.CanonicalLess
		}
		if less(order, value.Occurrences[occurrenceIndex], value.Occurrences[occurrenceIndex-1]) {
			issues = append(issues, fmt.Sprintf("occurrences[%d] is out of canonical order", occurrenceIndex))
		}
	}
	return issues
}

func sourceRefsValid(index source.DocumentIndex, value dnd.ItemOccurrenceList) bool {
	for _, occurrence := range value.Occurrences {
		if !itemoccurrencemodel.ValidSourceRefs(index, occurrence.SourceRefs) {
			return false
		}
	}
	return true
}

func Spec() pipeline.ValidatorSpec {
	return pipeline.ValidatorSpec{Key: Key, ExecutionClass: contracts.ExecutionClassDeterministic}
}

func Register(registry *pipeline.ValidatorRegistry) error {
	return pipeline.RegisterTypedValidatorBuilder(registry, dnd.ItemOccurrenceListKind, Spec(), validateOptions, func(request pipeline.BuildRequest) (contracts.TypedValidator[dnd.ItemOccurrenceList], 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 }
