package at.procon.dip.vectorization.startup;

import at.procon.dip.domain.document.EmbeddingStatus;
import at.procon.dip.domain.document.repository.DocumentEmbeddingRepository;
import at.procon.dip.runtime.condition.ConditionalOnRuntimeMode;
import at.procon.dip.runtime.config.RuntimeMode;
import at.procon.ted.config.LegacyVectorizationProperties;
import java.util.List;
import java.util.UUID;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.camel.ProducerTemplate;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Component;

/**
 * Queues pending and failed DOC embeddings immediately on startup for the legacy runtime graph.
 */
@Component
@ConditionalOnRuntimeMode(RuntimeMode.LEGACY)
@RequiredArgsConstructor
@Slf4j
public class GenericVectorizationStartupRunner implements ApplicationRunner {

    private static final int BATCH_SIZE = 1000;

    private final LegacyVectorizationProperties properties;
    private final DocumentEmbeddingRepository embeddingRepository;
    private final ProducerTemplate producerTemplate;

    @Override
    public void run(ApplicationArguments args) {
        if (!properties.isEnabled() || !properties.isGenericPipelineEnabled()) {
            return;
        }

        int queued = 0;
        queued += queueByStatus(EmbeddingStatus.PENDING, "PENDING");
        queued += queueByStatus(EmbeddingStatus.FAILED, "FAILED");
        log.info("Legacy generic vectorization startup runner queued {} embedding jobs", queued);
    }

    private int queueByStatus(EmbeddingStatus status, String label) {
        int queued = 0;
        int page = 0;
        List<UUID> ids;
        do {
            ids = embeddingRepository.findIdsByEmbeddingStatus(status, PageRequest.of(page, BATCH_SIZE));
            for (UUID id : ids) {
                try {
                    producerTemplate.sendBodyAndHeader("direct:vectorize-embedding", null, "embeddingId", id);
                    queued++;
                } catch (Exception e) {
                    log.warn("Failed to queue {} embedding {}: {}", label, id, e.getMessage());
                }
            }
            page++;
        } while (ids.size() == BATCH_SIZE);
        return queued;
    }
}