package at.procon.dip.normalization.service;

import at.procon.dip.normalization.spi.RepresentationBuildRequest;
import at.procon.dip.normalization.spi.TextRepresentationBuilder;
import at.procon.dip.normalization.spi.TextRepresentationDraft;
import java.util.ArrayList;
import java.util.List;
import lombok.RequiredArgsConstructor;
import org.springframework.core.annotation.AnnotationAwareOrderComparator;
import org.springframework.stereotype.Service;

@Service
@RequiredArgsConstructor
public class TextRepresentationBuildService {

    private final List<TextRepresentationBuilder> builders;

    public List<TextRepresentationDraft> build(RepresentationBuildRequest request) {
        List<TextRepresentationBuilder> matchingBuilders = builders.stream()
                .filter(builder -> builder.supports(request.detectionResult().documentType()))
                .sorted(AnnotationAwareOrderComparator.INSTANCE)
                .toList();
        if (matchingBuilders.isEmpty()) {
            throw new IllegalStateException(
                    "No text representation builder registered for " + request.detectionResult().documentType());
        }

        List<TextRepresentationDraft> result = new ArrayList<>();
        for (TextRepresentationBuilder builder : matchingBuilders) {
            List<TextRepresentationDraft> drafts = builder.build(request);
            if (drafts != null && !drafts.isEmpty()) {
                result.addAll(drafts);
            }
        }
        return result;
    }
}
