package pipeline

import (
	"fmt"
	"strings"

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

type OutputEncoderConstructor func() (contracts.OutputEncoder, error)
type OutputEncoderBuilder func(BuildRequest) (contracts.OutputEncoder, error)

type OutputProfileOptionContext struct {
	LaneIDs []string
}

type OutputProfileOptionValidator func(OutputProfileOptionContext, map[string]any) error

type OutputEncoderRegistry struct {
	builders          map[string]OutputEncoderBuilder
	optionValidators  map[string]OptionValidator
	profileValidators map[string]OutputProfileOptionValidator
	specs             map[string]ModuleSpec
}

func NewOutputEncoderRegistry() *OutputEncoderRegistry {
	return &OutputEncoderRegistry{
		builders:          make(map[string]OutputEncoderBuilder),
		optionValidators:  make(map[string]OptionValidator),
		profileValidators: make(map[string]OutputProfileOptionValidator),
		specs:             make(map[string]ModuleSpec),
	}
}

func (r *OutputEncoderRegistry) RegisterWithSpec(spec ModuleSpec, constructor OutputEncoderConstructor) error {
	if constructor == nil {
		return fmt.Errorf("output encoder constructor for %q must not be nil", strings.TrimSpace(spec.Key))
	}
	return r.RegisterBuilderWithSpec(spec, rejectUnconfiguredOptions, func(BuildRequest) (contracts.OutputEncoder, error) {
		return constructor()
	})
}

func (r *OutputEncoderRegistry) RegisterBuilderWithSpec(spec ModuleSpec, validateOptions OptionValidator, builder OutputEncoderBuilder) error {
	return r.RegisterBuilderWithProfileValidation(spec, validateOptions, nil, builder)
}

// RegisterBuilderWithProfileValidation registers an output builder with an
// optional validator that can inspect all configured lane identities.
func (r *OutputEncoderRegistry) RegisterBuilderWithProfileValidation(spec ModuleSpec, validateOptions OptionValidator, validateProfile OutputProfileOptionValidator, builder OutputEncoderBuilder) error {
	if r == nil {
		return fmt.Errorf("output encoder registry must not be nil")
	}

	normalizedSpec := normalizeModuleSpec(spec)
	if err := validateModuleSpec("output encoder", StageOutput, normalizedSpec); err != nil {
		return err
	}
	if validateOptions == nil {
		return fmt.Errorf("output encoder option validator for %q must not be nil", normalizedSpec.Key)
	}
	if builder == nil {
		return fmt.Errorf("output encoder builder for %q must not be nil", normalizedSpec.Key)
	}
	if _, ok := r.builders[normalizedSpec.Key]; ok {
		return fmt.Errorf("output encoder %q is already registered", normalizedSpec.Key)
	}

	if r.builders == nil {
		r.builders = make(map[string]OutputEncoderBuilder)
	}
	if r.optionValidators == nil {
		r.optionValidators = make(map[string]OptionValidator)
	}
	if r.profileValidators == nil {
		r.profileValidators = make(map[string]OutputProfileOptionValidator)
	}
	if r.specs == nil {
		r.specs = make(map[string]ModuleSpec)
	}
	r.builders[normalizedSpec.Key] = builder
	r.optionValidators[normalizedSpec.Key] = validateOptions
	r.profileValidators[normalizedSpec.Key] = validateProfile
	r.specs[normalizedSpec.Key] = cloneModuleSpec(normalizedSpec)
	return nil
}

func (r *OutputEncoderRegistry) Build(key string) (contracts.OutputEncoder, error) {
	return r.BuildWithRequest(key, BuildRequest{})
}

func (r *OutputEncoderRegistry) BuildWithRequest(key string, request BuildRequest) (contracts.OutputEncoder, error) {
	if r == nil {
		return nil, fmt.Errorf("output encoder registry must not be nil")
	}

	normalizedKey := strings.TrimSpace(key)
	if normalizedKey == "" {
		return nil, fmt.Errorf("output encoder key must not be empty")
	}

	builder, ok := r.builders[normalizedKey]
	if !ok {
		return nil, fmt.Errorf("output encoder %q is not registered", normalizedKey)
	}

	encoder, err := builder(cloneBuildRequest(request))
	if err != nil {
		return nil, fmt.Errorf("build output encoder %q: %w", normalizedKey, err)
	}
	if encoder == nil {
		return nil, fmt.Errorf("output encoder %q constructor returned nil", normalizedKey)
	}
	if encoder.Key() != normalizedKey {
		return nil, fmt.Errorf("output encoder %q returned key %q", normalizedKey, encoder.Key())
	}

	return encoder, nil
}

func (r *OutputEncoderRegistry) ValidateOptions(key string, options map[string]any) error {
	if r == nil {
		return fmt.Errorf("output encoder registry must not be nil")
	}
	normalizedKey := strings.TrimSpace(key)
	validator, ok := r.optionValidators[normalizedKey]
	if !ok {
		return fmt.Errorf("output encoder %q is not registered", normalizedKey)
	}
	return validateRegisteredOptions(validator, options)
}

func (r *OutputEncoderRegistry) ValidateProfileOptions(key string, context OutputProfileOptionContext, options map[string]any) error {
	if r == nil {
		return fmt.Errorf("output encoder registry must not be nil")
	}
	normalizedKey := strings.TrimSpace(key)
	validator, ok := r.profileValidators[normalizedKey]
	if !ok {
		return fmt.Errorf("output encoder %q is not registered", normalizedKey)
	}
	if validator == nil {
		return nil
	}
	return validator(OutputProfileOptionContext{LaneIDs: append([]string(nil), context.LaneIDs...)}, cloneOptions(options))
}

func (r *OutputEncoderRegistry) Spec(key string) (ModuleSpec, bool) {
	if r == nil {
		return ModuleSpec{}, false
	}

	spec, ok := r.specs[strings.TrimSpace(key)]
	if !ok {
		return ModuleSpec{}, false
	}
	return cloneModuleSpec(spec), true
}

func (r *OutputEncoderRegistry) RegisteredKeys() []string {
	if r == nil {
		return nil
	}

	return sortedRegistryKeys(r.builders)
}
