package pipeline

import (
	"context"
	"fmt"
	"reflect"
	"strings"

	"gitea.maximumdirect.net/eric/notarius/internal/framework/contracts"
)

type NormalizerRegistry struct {
	typedEntries map[artifactVariantKey]typedNormalizerEntry
}

type typedNormalizerEntry struct {
	spec            ModuleSpec
	valueType       reflect.Type
	validateOptions OptionValidator
	builder         func(BuildRequest) (any, error)
	normalize       typedNormalizeOperation
}

func NewNormalizerRegistry() *NormalizerRegistry {
	return &NormalizerRegistry{
		typedEntries: make(map[artifactVariantKey]typedNormalizerEntry),
	}
}

func RegisterNormalizer[T any](registry *NormalizerRegistry, spec ModuleSpec, constructor func() (contracts.Normalizer[T], error)) error {
	if constructor == nil {
		return fmt.Errorf("normalizer constructor for %q must not be nil", strings.TrimSpace(spec.Key))
	}
	return RegisterNormalizerBuilder(registry, spec, rejectUnconfiguredOptions, func(BuildRequest) (contracts.Normalizer[T], error) {
		return constructor()
	})
}

func RegisterNormalizerBuilder[T any](registry *NormalizerRegistry, spec ModuleSpec, validateOptions OptionValidator, builder func(BuildRequest) (contracts.Normalizer[T], error)) error {
	if registry == nil {
		return fmt.Errorf("normalizer registry must not be nil")
	}
	normalizedSpec := normalizeModuleSpec(spec)
	if err := validateModuleSpec("normalizer", StageNormalize, normalizedSpec); err != nil {
		return err
	}
	if normalizedSpec.ArtifactKind == "" {
		return fmt.Errorf("typed normalizer %q artifact kind must not be empty", normalizedSpec.Key)
	}
	if validateOptions == nil {
		return fmt.Errorf("normalizer option validator for %q must not be nil", normalizedSpec.Key)
	}
	if builder == nil {
		return fmt.Errorf("normalizer builder for %q must not be nil", normalizedSpec.Key)
	}
	key := artifactVariantKey{module: normalizedSpec.Key, kind: normalizedSpec.ArtifactKind}
	if _, ok := registry.typedEntries[key]; ok {
		return fmt.Errorf("normalizer %q variant for artifact kind %q is already registered", key.module, key.kind)
	}
	if registry.typedEntries == nil {
		registry.typedEntries = make(map[artifactVariantKey]typedNormalizerEntry)
	}
	registry.typedEntries[key] = typedNormalizerEntry{
		spec:            cloneModuleSpec(normalizedSpec),
		valueType:       reflect.TypeFor[T](),
		validateOptions: validateOptions,
		builder: func(request BuildRequest) (any, error) {
			return builder(cloneBuildRequest(request))
		},
		normalize: func(ctx context.Context, implementation any, request contracts.TypedNormalizeRequest[any]) (erasedTypedResult, error) {
			normalizer, ok := implementation.(contracts.Normalizer[T])
			if !ok {
				return erasedTypedResult{}, fmt.Errorf("normalizer %q has incompatible implementation %T", normalizedSpec.Key, implementation)
			}
			value, err := exactTypedValue[T]("normalize merge value", request.MergeOutput.Value)
			if err != nil {
				return erasedTypedResult{}, err
			}
			correction, err := contracts.CloneSemanticCorrection(request.Correction)
			if err != nil {
				return erasedTypedResult{}, fmt.Errorf("clone normalize correction: %w", err)
			}
			result, err := normalizer.Normalize(ctx, contracts.TypedNormalizeRequest[T]{Source: request.Source, LaneID: request.LaneID, MergeOutput: contracts.MergeArtifact[T]{LaneID: request.MergeOutput.LaneID, MergerKey: request.MergeOutput.MergerKey, SourceID: request.MergeOutput.SourceID, Value: value}, SourceInput: request.SourceInput, SessionID: request.SessionID, References: request.References, LLMProfile: request.LLMProfile, StructuredOutputRepairAttempts: request.StructuredOutputRepairAttempts, Correction: correction, Metadata: request.Metadata})
			if err != nil {
				return erasedTypedResult{}, err
			}
			candidate, err := contracts.CloneModelCandidate(result.ModelCandidate)
			if err != nil {
				return erasedTypedResult{}, fmt.Errorf("clone normalize model candidate: %w", err)
			}
			return erasedTypedResult{Value: result.Value, Diagnostics: contracts.CloneProducerDiagnostics(result.Diagnostics), Retry: cloneNormalizeRetry(result.Retry), ModelCandidate: candidate}, nil
		},
	}
	return nil
}

func cloneNormalizeRetry(retry *contracts.NormalizeRetry) *contracts.NormalizeRetry {
	if retry == nil {
		return nil
	}
	return &contracts.NormalizeRetry{
		ReasonCode:          retry.ReasonCode,
		Message:             retry.Message,
		CorrectionGuidance:  retry.CorrectionGuidance,
		FallbackDiagnostics: contracts.CloneProducerDiagnostics(retry.FallbackDiagnostics),
	}
}

func (r *NormalizerRegistry) validateOptions(key string, kind contracts.ArtifactKind, options map[string]any) error {
	if r == nil {
		return fmt.Errorf("normalizer registry must not be nil")
	}
	normalizedKey := strings.TrimSpace(key)
	entry, ok := r.typedEntry(normalizedKey, kind)
	if !ok {
		return fmt.Errorf("normalizer %q variant for artifact kind %q is not registered", normalizedKey, kind)
	}
	return validateRegisteredOptions(entry.validateOptions, options)
}

func (r *NormalizerRegistry) Spec(key string) (ModuleSpec, bool) {
	// Spec is for kind-neutral catalog inspection. Behavior-sensitive callers
	// must use SpecForArtifact so they select the lane's exact typed variant.
	kinds := r.registeredKinds(key)
	if len(kinds) == 0 {
		return ModuleSpec{}, false
	}
	return r.SpecForArtifact(key, kinds[0])
}

// SpecForArtifact returns the normalizer spec registered for an exact artifact kind.
func (r *NormalizerRegistry) SpecForArtifact(key string, kind contracts.ArtifactKind) (ModuleSpec, bool) {
	entry, ok := r.typedEntry(key, kind)
	if !ok {
		return ModuleSpec{}, false
	}
	return cloneModuleSpec(entry.spec), true
}

// RegisteredArtifactKinds returns the sorted artifact kinds registered for a
// normalizer key.
func (r *NormalizerRegistry) RegisteredArtifactKinds(key string) []contracts.ArtifactKind {
	return r.registeredKinds(key)
}

func (r *NormalizerRegistry) typedEntry(key string, kind contracts.ArtifactKind) (typedNormalizerEntry, bool) {
	if r == nil {
		return typedNormalizerEntry{}, false
	}
	entry, ok := r.typedEntries[artifactVariantKey{module: strings.TrimSpace(key), kind: normalizeArtifactKind(kind)}]
	return entry, ok
}

func (r *NormalizerRegistry) registeredKinds(key string) []contracts.ArtifactKind {
	if r == nil {
		return nil
	}
	module := strings.TrimSpace(key)
	kinds := make([]contracts.ArtifactKind, 0)
	for variant := range r.typedEntries {
		if variant.module == module {
			kinds = append(kinds, variant.kind)
		}
	}
	sortArtifactKinds(kinds)
	return kinds
}

func (r *NormalizerRegistry) RegisteredKeys() []string {
	if r == nil {
		return nil
	}
	keys := make(map[string]struct{}, len(r.typedEntries))
	for key := range r.typedEntries {
		keys[key.module] = struct{}{}
	}
	return sortedRegistryKeys(keys)
}
