package pipeline

import (
	"fmt"
	"strings"

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

type InputAdapterConstructor func() (contracts.InputAdapter, error)
type InputAdapterBuilder func(BuildRequest) (contracts.InputAdapter, error)

type InputAdapterRegistry struct {
	builders         map[string]InputAdapterBuilder
	optionValidators map[string]OptionValidator
	specs            map[string]ModuleSpec
}

func NewInputAdapterRegistry() *InputAdapterRegistry {
	return &InputAdapterRegistry{
		builders:         make(map[string]InputAdapterBuilder),
		optionValidators: make(map[string]OptionValidator),
		specs:            make(map[string]ModuleSpec),
	}
}

func (r *InputAdapterRegistry) RegisterWithSpec(spec ModuleSpec, constructor InputAdapterConstructor) error {
	if constructor == nil {
		return fmt.Errorf("input adapter constructor for %q must not be nil", strings.TrimSpace(spec.Key))
	}
	return r.RegisterBuilderWithSpec(spec, rejectUnconfiguredOptions, func(BuildRequest) (contracts.InputAdapter, error) {
		return constructor()
	})
}

func (r *InputAdapterRegistry) RegisterBuilderWithSpec(spec ModuleSpec, validateOptions OptionValidator, builder InputAdapterBuilder) error {
	if r == nil {
		return fmt.Errorf("input adapter registry must not be nil")
	}

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

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

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

func (r *InputAdapterRegistry) BuildWithRequest(key string, request BuildRequest) (contracts.InputAdapter, error) {
	if r == nil {
		return nil, fmt.Errorf("input adapter registry must not be nil")
	}

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

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

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

	return adapter, nil
}

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

func (r *InputAdapterRegistry) 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 *InputAdapterRegistry) RegisteredKeys() []string {
	if r == nil {
		return nil
	}

	return sortedRegistryKeys(r.builders)
}
