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/shared/diagnostics"
)

const (
	Key        = "extract/dnd/npc-registry/shape"
	ReasonCode = "invalid_npc_shape"
	policy     = "dnd.npc_registry.validator.shape.v2"
)

type Options struct{}
type Validator struct{}

var _ contracts.TypedValidator[dnd.NPCRegistry] = (*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.NPCRegistry]) (contracts.ValidationResult, error) {
	normalization := req.Stage == string(pipeline.StageNormalize)
	issues, corrections := assess(req.Value, normalization)
	if len(issues) > 0 {
		prefix := "Correct every rejected NPC and return the complete replacement registry"
		if normalization {
			prefix = "Correct the duplicate-group proposals and return the complete replacement proposal response"
		}
		return rejection(diagnostics.Aggregate("invalid NPC shape", issues), corrections.Guidance(prefix)), nil
	}
	return contracts.ValidationResult{Approved: true}, nil
}

func Validate(value dnd.NPCRegistry) error {
	issues, _ := assess(value, false)
	if len(issues) == 0 {
		return nil
	}
	return fmt.Errorf("%s", diagnostics.Aggregate("invalid NPC shape", issues))
}

func assess(value dnd.NPCRegistry, normalization bool) ([]string, diagnostics.Corrections) {
	var corrections diagnostics.Corrections
	nameRule := "Provide one nonblank, transcript-supported proper NPC name for every registry entry."
	refRule := "Provide at least one transcript source range that directly supports every named NPC."
	listRule := "Return an `npcs` array; use an empty array when the transcript establishes no named NPCs."
	if normalization {
		nameRule = "Revise the duplicate-group proposals so every selected canonical NPC has a nonblank, transcript-supported proper name."
		refRule = "Revise the duplicate-group proposals so every selected canonical NPC preserves direct transcript evidence."
		listRule = "Revise the duplicate-group proposals so normalization retains the complete NPC candidate registry."
	}
	issues := make([]string, 0)
	if value.NPCs == nil {
		corrections.Add("list", listRule, "")
		return []string{"npcs must be present"}, corrections
	}
	for index, npc := range value.NPCs {
		prefix := fmt.Sprintf("npcs[%d]", index)
		record := "Affected NPC " + diagnostics.Quote(strings.TrimSpace(npc.Name)) + " " + diagnostics.SourceRange(npc.SourceRefs) + "."
		if strings.TrimSpace(npc.ID) == "" {
			issues = append(issues, prefix+".id must not be empty")
			corrections.Add("name", nameRule, record)
		}
		if strings.TrimSpace(npc.Name) == "" {
			issues = append(issues, prefix+".name must not be empty")
			corrections.Add("name", nameRule, record)
		}
		if len(npc.SourceRefs) == 0 {
			issues = append(issues, prefix+".source_refs must not be empty")
			corrections.Add("source-refs", refRule, record)
		}
	}
	return issues, corrections
}

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

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

func rejection(message, guidance string) contracts.ValidationResult {
	return contracts.ValidationResult{Approved: false, ReasonCode: ReasonCode, Message: message, CorrectionGuidance: guidance}
}
