package at.procon.dip.processing.service;

import at.procon.dip.classification.spi.DetectionResult;
import at.procon.dip.extraction.spi.ExtractionResult;
import at.procon.dip.ingestion.spi.SourceDescriptor;
import at.procon.dip.processing.spi.DocumentProcessingPolicy;
import at.procon.dip.processing.spi.StructuredDocumentProcessor;
import at.procon.dip.processing.spi.StructuredProcessingRequest;
import java.util.List;
import java.util.Optional;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

@Service
@RequiredArgsConstructor
public class StructuredDocumentProcessingService {

    private final List<StructuredDocumentProcessor> processors;

    public Optional<StructuredDocumentProcessor> resolve(SourceDescriptor sourceDescriptor, DetectionResult detectionResult) {
        return processors.stream()
                .filter(processor -> processor.supports(sourceDescriptor, detectionResult))
                .findFirst();
    }

    public DocumentProcessingPolicy resolvePolicy(SourceDescriptor sourceDescriptor, DetectionResult detectionResult) {
        return resolve(sourceDescriptor, detectionResult)
                .map(processor -> processor.processingPolicy(sourceDescriptor, detectionResult))
                .orElse(DocumentProcessingPolicy.genericDefault());
    }

    public Optional<ExtractionResult> process(StructuredProcessingRequest request) {
        return resolve(request.sourceDescriptor(), request.detectionResult())
                .map(processor -> processor.process(request));
    }
}
