// Package shape validates required D&D item-occurrence candidate fields.
package shape

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

const (
	Key        = "extract/dnd/item-occurrences/shape"
	ReasonCode = "invalid_item_occurrence_shape"
	policy     = "dnd.item_occurrences.shape.v3"
)

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) {
	assessment := assess(req.Value)
	if len(assessment.operatorIssues) != 0 {
		return contracts.ValidationResult{
			Approved:           false,
			ReasonCode:         ReasonCode,
			Message:            assessment.operatorMessage(),
			CorrectionGuidance: assessment.correctionGuidance(),
		}, nil
	}
	return contracts.ValidationResult{Approved: true}, nil
}

// Validate returns one bounded error for every owned item-occurrence shape issue.
func Validate(value dnd.ItemOccurrenceList) error {
	assessment := assess(value)
	if len(assessment.operatorIssues) == 0 {
		return nil
	}
	return fmt.Errorf("%s", assessment.operatorMessage())
}

type validationAssessment struct {
	operatorIssues []string
	corrections    diagnostics.Corrections
}

func assess(value dnd.ItemOccurrenceList) validationAssessment {
	var assessment validationAssessment
	if value.Occurrences == nil {
		assessment.operatorIssues = append(assessment.operatorIssues, "occurrences must be present")
		assessment.addCorrection("occurrences", "item-occurrence list", "Return an `occurrences` array; use an empty array when the transcript establishes no occurrences.", "")
		return assessment
	}
	for index, occurrence := range value.Occurrences {
		prefix := fmt.Sprintf("occurrences[%d]", index)
		context := occurrenceContext(occurrence)
		if strings.TrimSpace(occurrence.ItemID) == "" {
			assessment.operatorIssues = append(assessment.operatorIssues, prefix+".item_id must not be empty: "+diagnostics.Quote(occurrence.ItemID))
			assessment.addCorrection("item-name", "item name", "Select a contextual item name from the supplied item registry for every occurrence.", context)
		}
		if strings.TrimSpace(occurrence.Name) == "" {
			assessment.operatorIssues = append(assessment.operatorIssues, prefix+".name must not be empty: "+diagnostics.Quote(occurrence.Name))
			assessment.addCorrection("item-name", "item name", "Select a contextual item name from the supplied item registry for every occurrence.", context)
		}
		if !itemoccurrences.SupportedKind(occurrence.Kind) {
			assessment.operatorIssues = append(assessment.operatorIssues, prefix+".kind is unsupported: "+diagnostics.Quote(string(occurrence.Kind)))
			assessment.addCorrection("kind", "occurrence kind", "Set `kind` to exactly one of `discovered`, `acquired`, `lost`, `consumed`, or `transferred`.", context)
		} else if !itemoccurrences.ValidHolderCombination(occurrence.Kind, occurrence.From, occurrence.To) {
			assessment.operatorIssues = append(assessment.operatorIssues, prefix+holderOperatorIssue(occurrence))
			assessment.addCorrection("holders:"+string(occurrence.Kind), string(occurrence.Kind)+" holders", holderCorrection(occurrence.Kind), context)
		}
		if occurrence.Quantity != nil && *occurrence.Quantity < 1 {
			assessment.operatorIssues = append(assessment.operatorIssues, prefix+".quantity must be positive when present")
			assessment.addCorrection("quantity", "quantity", "Set `quantity` to a positive integer when the transcript states one, or to JSON null when it does not.", context)
		}
		if len(occurrence.SourceRefs) == 0 {
			assessment.operatorIssues = append(assessment.operatorIssues, prefix+".source_refs must contain at least one reference")
			assessment.addCorrection("source-refs", "source references", "Provide at least one transcript source range that directly supports every occurrence.", context)
		}
	}
	return assessment
}

func (assessment *validationAssessment) addCorrection(key, label, rule, record string) {
	if record != "" {
		record = "Affected " + label + " record: " + record
	}
	assessment.corrections.Add(key, rule, record)
}

func (assessment validationAssessment) operatorMessage() string {
	return diagnostics.Aggregate("invalid item occurrence shape", assessment.operatorIssues)
}

func (assessment validationAssessment) correctionGuidance() string {
	return assessment.corrections.Guidance("Correct every rejected item occurrence and return the complete replacement list")
}

func holderOperatorIssue(occurrence dnd.ItemOccurrence) string {
	return fmt.Sprintf(
		".from and .to are incompatible with %s: expected %s; got from %s and to %s",
		diagnostics.Quote(string(occurrence.Kind)), holderExpectation(occurrence.Kind),
		holderDisplay(occurrence.From), holderDisplay(occurrence.To),
	)
}

func holderExpectation(kind dnd.ItemOccurrenceKind) string {
	switch kind {
	case dnd.ItemOccurrenceKindDiscovered:
		return "both holders absent"
	case dnd.ItemOccurrenceKindAcquired:
		return "from absent and to present"
	case dnd.ItemOccurrenceKindLost:
		return "from present and to absent"
	case dnd.ItemOccurrenceKindConsumed:
		return "from present and to absent"
	case dnd.ItemOccurrenceKindTransferred:
		return "distinct named party-member holders"
	default:
		return "a supported holder combination"
	}
}

func holderCorrection(kind dnd.ItemOccurrenceKind) string {
	switch kind {
	case dnd.ItemOccurrenceKindDiscovered:
		return "For `discovered` occurrences, set both `from` and `to` to JSON null."
	case dnd.ItemOccurrenceKindAcquired:
		return "For `acquired` occurrences, set `from` to JSON null and `to` to `party` or the named party member gaining possession."
	case dnd.ItemOccurrenceKindLost:
		return "For `lost` occurrences, set `from` to `party` or the named party member losing possession and set `to` to JSON null."
	case dnd.ItemOccurrenceKindConsumed:
		return "For `consumed` occurrences, set `from` to `party` or the named party member consuming the item and set `to` to JSON null."
	case dnd.ItemOccurrenceKindTransferred:
		return "For `transferred` occurrences, set `from` and `to` to two distinct named party members; never use `party` for either holder."
	default:
		return "Use the holder combination required by the selected supported occurrence kind."
	}
}

func occurrenceContext(occurrence dnd.ItemOccurrence) string {
	name := itemoccurrences.DisplayValue(occurrence.Name)
	context := "item " + diagnostics.Quote(name)
	if name == "" {
		context = "item with a blank contextual name"
	}
	context += " " + diagnostics.SourceRange(occurrence.SourceRefs)
	return context + " with from " + holderDisplay(occurrence.From) + " and to " + holderDisplay(occurrence.To)
}

func holderDisplay(value string) string {
	value = itemoccurrences.DisplayValue(value)
	if value == "" {
		return "JSON null"
	}
	return diagnostics.Quote(value)
}

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 }
