package at.procon.dip.embedding.startup;

import at.procon.dip.embedding.config.EmbeddingProperties;
import at.procon.dip.embedding.model.EmbeddingPrefixMode;
import at.procon.dip.embedding.registry.EmbeddingModelRegistry;
import at.procon.dip.embedding.registry.EmbeddingProviderConfigResolver;
import at.procon.dip.embedding.registry.EmbeddingProviderRegistry;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;
import at.procon.dip.runtime.condition.ConditionalOnRuntimeMode;
import at.procon.dip.runtime.config.RuntimeMode;

@Component
@RequiredArgsConstructor
@ConditionalOnProperty(prefix = "dip.embedding", name = "enabled", havingValue = "true")
@Slf4j
@ConditionalOnRuntimeMode(RuntimeMode.NEW)
public class EmbeddingSubsystemStartupValidator implements ApplicationRunner {

    private final EmbeddingProperties properties;
    private final EmbeddingModelRegistry modelRegistry;
    private final EmbeddingProviderConfigResolver providerConfigResolver;
    private final EmbeddingProviderRegistry providerRegistry;

    @Override
    public void run(ApplicationArguments args) {
        if (properties.getModels().isEmpty()) {
            throw new IllegalStateException("dip.embedding.enabled=true but no models are configured");
        }

        modelRegistry.getActiveModels().forEach(model -> {
            var providerConfig = providerConfigResolver.resolve(model.providerConfigKey());
            providerRegistry.getRequired(providerConfig.providerType());
            if (model.prefixMode() == EmbeddingPrefixMode.CLIENT) {
                if (model.queryPrefix() == null || model.queryPrefix().isBlank()) {
                    throw new IllegalStateException("Embedding model " + model.modelKey() + " uses CLIENT prefix mode but query-prefix is blank");
                }
                if (model.documentPrefix() == null || model.documentPrefix().isBlank()) {
                    throw new IllegalStateException("Embedding model " + model.modelKey() + " uses CLIENT prefix mode but document-prefix is blank");
                }
            }
            log.info("Validated embedding model {} -> provider {} ({}, prefixMode={})",
                    model.modelKey(), model.providerConfigKey(), providerConfig.providerType(), model.prefixMode());
        });

        if (properties.getDefaultDocumentModel() != null && !properties.getDefaultDocumentModel().isBlank()) {
            modelRegistry.getRequired(properties.getDefaultDocumentModel());
        }
        if (properties.getDefaultQueryModel() != null && !properties.getDefaultQueryModel().isBlank()) {
            modelRegistry.getRequired(properties.getDefaultQueryModel());
        }
    }
}
