package catalog

import (
	"context"
	"fmt"
	"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/diagnostics"
	spellcatalog "gitea.maximumdirect.net/eric/notarius/internal/modules/dnd/spells/catalog"
	spellshape "gitea.maximumdirect.net/eric/notarius/internal/modules/dnd/validate/spells/shape"
)

const (
	Key        = "extract/dnd/spells/catalog"
	ReasonCode = "unknown_spell"
	policy     = "dnd.spells.validator.catalog.v2"
)

type Options struct{}

type Validator struct {
	catalog spellcatalog.EffectiveCatalog
}

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

func New(_ Options, references ...contracts.ReferenceSet) (*Validator, error) {
	if len(references) > 1 {
		return nil, fmt.Errorf("spell catalog validator accepts at most one reference set")
	}
	var referenceSet contracts.ReferenceSet
	if len(references) == 1 {
		referenceSet = references[0]
	}
	effective, err := spellcatalog.ResolveEffectiveCatalog(referenceSet)
	if err != nil {
		return nil, err
	}
	return &Validator{catalog: effective}, nil
}

func (v *Validator) Name() string { return Key }

func (v *Validator) ExecutionClass() contracts.ExecutionClass {
	return contracts.ExecutionClassDeterministic
}

func (v *Validator) CheckpointFingerprints() []pipeline.CheckpointFingerprint {
	if v == nil {
		return nil
	}
	return []pipeline.CheckpointFingerprint{
		{Name: "policy", Value: policy},
		{Name: "effective_catalog", Value: v.catalog.Digest()},
	}
}

func (v *Validator) Validate(_ context.Context, req contracts.TypedValidationRequest[dnd.SpellList]) (contracts.ValidationResult, error) {
	if err := spellshape.Validate(req.Value); err != nil {
		return contracts.ValidationResult{Approved: true}, nil
	}

	unknown := make([]unknownSpell, 0)
	for index, spell := range req.Value.SpellCasts {
		name := strings.TrimSpace(spell.Spell)
		if name == "" {
			continue
		}
		if _, ok := v.catalog.Lookup(name); !ok {
			unknown = append(unknown, unknownSpell{index: index, name: name, caster: spell.Caster, sourceRefs: spell.SourceRefs})
		}
	}
	if len(unknown) == 0 {
		return contracts.ValidationResult{Approved: true}, nil
	}
	return rejection(unknown), nil
}

type unknownSpell struct {
	index      int
	name       string
	caster     string
	sourceRefs []source.SourceRef
}

func rejection(unknown []unknownSpell) contracts.ValidationResult {
	issues := make([]string, 0, len(unknown))
	var corrections diagnostics.Corrections
	for _, item := range unknown {
		issues = append(issues, fmt.Sprintf("spell_casts[%d].spell %s", item.index, diagnostics.Quote(item.name)))
		corrections.Add(
			"recognized-spell",
			"Use a recognized D&D spell name supported by the transcript, or omit the record when the evidence does not establish a spell cast.",
			fmt.Sprintf("Affected spell %s by caster %s %s.", diagnostics.Quote(item.name), diagnostics.Quote(strings.TrimSpace(item.caster)), diagnostics.SourceRange(item.sourceRefs)),
		)
	}
	return contracts.ValidationResult{
		Approved:           false,
		ReasonCode:         ReasonCode,
		Message:            diagnostics.Aggregate("unknown spell names", issues),
		CorrectionGuidance: corrections.Guidance("Correct every unrecognized spell and return the complete replacement spell-cast list"),
	}
}

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

func Register(registry *pipeline.ValidatorRegistry) error {
	return pipeline.RegisterTypedValidatorBuilder(registry, dnd.SpellListKind, Spec(), validateOptions, func(request pipeline.BuildRequest) (contracts.TypedValidator[dnd.SpellList], error) {
		options, err := DecodeOptions(request.Options)
		if err != nil {
			return nil, err
		}
		return New(options, request.References)
	})
}

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 }
