package at.procon.dip.extraction.impl;

import at.procon.dip.domain.document.ContentRole;
import at.procon.dip.domain.document.DocumentType;
import at.procon.dip.extraction.spi.ExtractedStructuredPayload;
import at.procon.dip.extraction.spi.DocumentExtractor;
import at.procon.dip.extraction.spi.ExtractionRequest;
import at.procon.dip.extraction.spi.ExtractionResult;
import at.procon.ted.service.attachment.PdfExtractionService;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

@Component
@RequiredArgsConstructor
public class PdfDocumentExtractor implements DocumentExtractor {

    private final PdfExtractionService pdfExtractionService;

    @Override
    public boolean supports(DocumentType documentType, String mimeType) {
        return documentType == DocumentType.PDF;
    }

    @Override
    public ExtractionResult extract(ExtractionRequest extractionRequest) {
        byte[] binary = extractionRequest.binaryContent();
        if (binary == null || binary.length == 0) {
            return new ExtractionResult(Map.of(), List.of(), List.of("No PDF binary payload available"));
        }

        PdfExtractionService.ExtractionResult extraction = pdfExtractionService.extract(
                binary,
                extractionRequest.sourceDescriptor().fileName(),
                extractionRequest.detectionResult().mimeType()
        );
        if (!extraction.success()) {
            return new ExtractionResult(Map.of(), List.of(), List.of(extraction.errorMessage()));
        }

        String text = extraction.extractedText();
        if (!StringUtils.hasText(text)) {
            return new ExtractionResult(Map.of(), List.of(), List.of("PDF text extraction returned no text"));
        }

        Map<String, Object> payload = new LinkedHashMap<>();
        payload.put("title", deriveTitle(text, extractionRequest.sourceDescriptor().fileName()));
        payload.put("extractor", "pdfbox");

        return new ExtractionResult(
                Map.of(ContentRole.NORMALIZED_TEXT, text),
                List.of(new ExtractedStructuredPayload("pdf-document", payload)),
                List.of()
        );
    }

    private String deriveTitle(String text, String fallback) {
        for (String line : text.split("\\n")) {
            if (StringUtils.hasText(line)) {
                String trimmed = line.trim();
                return trimmed.length() > 240 ? trimmed.substring(0, 240) : trimmed;
            }
        }
        return fallback;
    }
}
