// Package sourcerefs validates D&D scene-description source identity.
package sourcerefs

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

const (
	Key        = "extract/dnd/scene-descriptions/source_refs"
	ReasonCode = "invalid_scene_description_source_refs"
	policy     = "dnd.scene_descriptions.validator.source_refs.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.ValidateForStage(req.Value, req.Stage) != nil {
		return contracts.ValidationResult{Approved: true}, nil
	}
	issues := make([]string, 0)
	if req.Stage == string(pipeline.StageExtract) && req.Chunk == nil {
		issues = append(issues, "current extraction chunk must not be nil")
	}
	index := source.NewDocumentIndex(req.Source)
	for sceneIndex, scene := range req.Value.Scenes {
		prefix := fmt.Sprintf("scenes[%d]", sceneIndex)
		if err := index.ValidateRef(scene.SourceRef); err != nil {
			issues = append(issues, prefix+".source_ref: "+diagnostics.Truncate(err.Error()))
			continue
		}
		if req.Stage == string(pipeline.StageExtract) && req.Chunk != nil {
			if scene.ID != req.Chunk.ID {
				issues = append(issues, prefix+".id must equal the current extraction chunk ID")
			}
			if scene.SourceRef != req.Chunk.Ref {
				issues = append(issues, prefix+".source_ref must equal the current extraction chunk range")
			}
		}
	}
	if len(issues) == 0 {
		return contracts.ValidationResult{Approved: true}, nil
	}
	return contracts.ValidationResult{
		Approved:           false,
		ReasonCode:         ReasonCode,
		Message:            diagnostics.Aggregate("invalid scene description source references", issues),
		CorrectionGuidance: "Return exactly one scene description for the supplied chunk, using that chunk's scene identity and complete source range.",
	}, nil
}

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 }
