// Package register composes the production D&D module family.
package register

import (
	"fmt"

	"gitea.maximumdirect.net/eric/notarius/internal/framework/llm"
	"gitea.maximumdirect.net/eric/notarius/internal/framework/pipeline"
)

type registration struct {
	name     string
	register func() error
}

// Register adds all production D&D modules, validators, policy, and assets.
func Register(registries pipeline.Registries, assets *llm.AssetRegistry) error {
	if err := validateRegistries(registries, assets); err != nil {
		return err
	}
	if err := registerModules(registries); err != nil {
		return err
	}
	if err := registerEvidence(registries.ArtifactEvidence); err != nil {
		return err
	}
	if err := registerValidators(registries); err != nil {
		return err
	}
	if err := registerPromptAssets(assets); err != nil {
		return err
	}
	if err := registerFallbackProfiles(assets); err != nil {
		return err
	}
	return registerDefaultChains(registries.ValidatorChains)
}

func runRegistrations(registrations []registration) error {
	for _, registration := range registrations {
		if err := registration.register(); err != nil {
			return fmt.Errorf("register dnd %s: %w", registration.name, err)
		}
	}
	return nil
}

func validateRegistries(registries pipeline.Registries, assets *llm.AssetRegistry) error {
	switch {
	case registries.Chunkers == nil:
		return fmt.Errorf("dnd registrar: chunker registry must not be nil")
	case registries.ArtifactCodecs == nil:
		return fmt.Errorf("dnd registrar: artifact codec registry must not be nil")
	case registries.ArtifactEvidence == nil:
		return fmt.Errorf("dnd registrar: artifact evidence registry must not be nil")
	case registries.Extractors == nil:
		return fmt.Errorf("dnd registrar: extractor registry must not be nil")
	case registries.Mergers == nil:
		return fmt.Errorf("dnd registrar: merger registry must not be nil")
	case registries.Normalizers == nil:
		return fmt.Errorf("dnd registrar: normalizer registry must not be nil")
	case registries.Validators == nil:
		return fmt.Errorf("dnd registrar: validator registry must not be nil")
	case registries.ValidatorChains == nil:
		return fmt.Errorf("dnd registrar: validator chain registry must not be nil")
	case assets == nil:
		return fmt.Errorf("dnd registrar: asset registry must not be nil")
	default:
		return nil
	}
}
