// Package invariants validates normalized D&D scene description artifacts.
package invariants

import (
	"context"
	"fmt"
	"sort"

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

const (
	Key        = "normalize/dnd/scene-descriptions/invariants"
	ReasonCode = "invalid_scene_description_normalization"
	policy     = "dnd.scene_descriptions.validator.invariants.v1"
)

type Options struct{}
type Validator struct{}

var _ contracts.TypedValidator[dnd.SceneDescriptionList] = (*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.SceneDescriptionList]) (contracts.ValidationResult, error) {
	if shape.Validate(req.Value) != nil {
		return contracts.ValidationResult{Approved: true}, nil
	}
	index := source.NewDocumentIndex(req.Source)
	if !sourceRefsValid(index, req.Value) {
		return contracts.ValidationResult{Approved: true}, nil
	}
	issues := issuesFor(index, req.Value)
	if len(issues) == 0 {
		return contracts.ValidationResult{Approved: true}, nil
	}
	return contracts.ValidationResult{
		Approved:           false,
		ReasonCode:         ReasonCode,
		Message:            diagnostics.Aggregate("invalid scene description normalization", issues),
		CorrectionGuidance: "Return scene descriptions in canonical source order, with one unique scene per source range and no duplicate scene identity.",
	}, nil
}

func sourceRefsValid(index source.DocumentIndex, value dnd.SceneDescriptionList) bool {
	for _, scene := range value.Scenes {
		if index.ValidateRef(scene.SourceRef) != nil {
			return false
		}
	}
	return true
}

func issuesFor(index source.DocumentIndex, value dnd.SceneDescriptionList) []string {
	issues := make([]string, 0)
	if !sort.SliceIsSorted(value.Scenes, func(left, right int) bool {
		leftStart, _ := index.Position(value.Scenes[left].SourceRef.StartUnitID)
		rightStart, _ := index.Position(value.Scenes[right].SourceRef.StartUnitID)
		if leftStart != rightStart {
			return leftStart < rightStart
		}
		return value.Scenes[left].ID < value.Scenes[right].ID
	}) {
		issues = append(issues, "scenes are not in canonical source order")
	}

	byID := make(map[string]int, len(value.Scenes))
	byRange := make(map[source.SourceRef]int, len(value.Scenes))
	for index, scene := range value.Scenes {
		if index > 0 && value.Scenes[index-1] == scene {
			issues = append(issues, fmt.Sprintf("scenes[%d] duplicates scenes[%d]", index, index-1))
		}
		if previous, ok := byID[scene.ID]; ok && value.Scenes[previous] != scene {
			issues = append(issues, fmt.Sprintf("scenes[%d] conflicts with scenes[%d] for scene ID", index, previous))
		} else if !ok {
			byID[scene.ID] = index
		}
		if previous, ok := byRange[scene.SourceRef]; ok && !sameModelContent(value.Scenes[previous], scene) {
			issues = append(issues, fmt.Sprintf("scenes[%d] conflicts with scenes[%d] for source range", index, previous))
		} else if !ok {
			byRange[scene.SourceRef] = index
		}
	}
	return issues
}

func sameModelContent(left, right dnd.SceneDescription) bool {
	return left.Kind == right.Kind && left.Title == right.Title && left.Summary == right.Summary
}

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

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