package catalog

import (
	"context"
	"fmt"
	"strings"

	"gitea.maximumdirect.net/eric/notarius/internal/framework/contracts"
	"gitea.maximumdirect.net/eric/notarius/internal/framework/pipeline"
	"gitea.maximumdirect.net/eric/notarius/internal/modules/dnd"
	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"
	maxIssues             = 20
	maxDisplayedNameRunes = 128
	maxMessageBytes       = 4096
)

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: "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})
		}
	}
	if len(unknown) == 0 {
		return contracts.ValidationResult{Approved: true}, nil
	}
	return rejection(unknown), nil
}

type unknownSpell struct {
	index int
	name  string
}

func rejection(unknown []unknownSpell) contracts.ValidationResult {
	limit := len(unknown)
	if limit > maxIssues {
		limit = maxIssues
	}
	issues := make([]string, 0, limit)
	for _, item := range unknown[:limit] {
		issue := fmt.Sprintf("spell_casts[%d].spell %q", item.index, truncateDisplayedName(item.name))
		candidate := rejectionMessage(append(issues, issue), len(unknown)-len(issues)-1)
		if len(candidate) > maxMessageBytes {
			break
		}
		issues = append(issues, issue)
	}
	message := rejectionMessage(issues, len(unknown)-len(issues))
	return contracts.ValidationResult{Approved: false, ReasonCode: ReasonCode, Message: message}
}

func truncateDisplayedName(name string) string {
	runes := []rune(name)
	if len(runes) <= maxDisplayedNameRunes {
		return name
	}
	return string(runes[:maxDisplayedNameRunes-1]) + "…"
}

func rejectionMessage(issues []string, omitted int) string {
	message := "unknown spell names: " + strings.Join(issues, ", ")
	if omitted > 0 {
		message += fmt.Sprintf("; %d additional issue(s) omitted", omitted)
	}
	return message
}

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 }
