package at.procon.dip.normalization.impl;

import at.procon.dip.domain.document.ContentRole;
import at.procon.dip.domain.document.DocumentType;
import at.procon.dip.domain.document.RepresentationType;
import at.procon.dip.extraction.spi.ExtractedStructuredPayload;
import at.procon.dip.ingestion.util.DocumentImportSupport;
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 java.util.Map;
import java.util.Objects;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

@Component
@Order(10)
public class TedStructuredTextRepresentationBuilder implements TextRepresentationBuilder {

    public static final String BUILDER_KEY = "ted-structured-text";

    @Override
    public boolean supports(DocumentType documentType) {
        return documentType == DocumentType.TED_NOTICE;
    }

    @Override
    public List<TextRepresentationDraft> build(RepresentationBuildRequest request) {
        String normalizedText = request.extractionResult().derivedTextByRole().get(ContentRole.NORMALIZED_TEXT);
        if (!StringUtils.hasText(normalizedText)) {
            return List.of();
        }

        Map<String, Object> attributes = request.extractionResult().structuredPayloads().stream()
                .filter(payload -> Objects.equals(payload.projectionName(), "ted-notice"))
                .map(ExtractedStructuredPayload::attributes)
                .filter(Objects::nonNull)
                .findFirst()
                .orElse(Map.of());

        String title = asString(attributes.get("title"));
        String description = asString(attributes.get("description"));
        String buyerName = asString(attributes.get("buyerName"));
        String cpvCodes = asString(attributes.get("cpvCodes"));
        String nutsCodes = asString(attributes.get("nutsCodes"));
        String publicationId = asString(attributes.get("publicationId"));
        String semanticText = buildSemanticText(title, description, buyerName, cpvCodes, nutsCodes, publicationId, normalizedText);
        String summary = DocumentImportSupport.ellipsize(
                StringUtils.hasText(description) ? description.trim() : normalizedText.replace('\n', ' ').trim(),
                1200
        );

        List<TextRepresentationDraft> drafts = new ArrayList<>();
        drafts.add(new TextRepresentationDraft(
                RepresentationType.SEMANTIC_TEXT,
                BUILDER_KEY,
                request.detectionResult().languageCode(),
                semanticText,
                true,
                null,
                null,
                null,
                ContentRole.NORMALIZED_TEXT,
                Boolean.TRUE
        ));
        /*
        drafts.add(new TextRepresentationDraft(
                RepresentationType.FULLTEXT,
                BUILDER_KEY,
                request.detectionResult().languageCode(),
                normalizedText,
                false,
                null,
                null,
                null,
                ContentRole.NORMALIZED_TEXT,
                Boolean.FALSE
        ));
        if (StringUtils.hasText(title)) {
            drafts.add(new TextRepresentationDraft(
                    RepresentationType.TITLE_ABSTRACT,
                    BUILDER_KEY,
                    request.detectionResult().languageCode(),
                    title + "\n\n" + summary,
                    false,
                    null,
                    null,
                    null,
                    ContentRole.NORMALIZED_TEXT,
                    Boolean.FALSE
            ));
        }
        drafts.add(new TextRepresentationDraft(
                RepresentationType.SUMMARY,
                BUILDER_KEY,
                request.detectionResult().languageCode(),
                summary,
                false,
                null,
                null,
                null,
                ContentRole.NORMALIZED_TEXT,
                Boolean.FALSE
        ));
         */
        return drafts;
    }

    private String buildSemanticText(String title,
                                     String description,
                                     String buyerName,
                                     String cpvCodes,
                                     String nutsCodes,
                                     String publicationId,
                                     String normalizedText) {
        StringBuilder sb = new StringBuilder();
        sb.append("Document type: TED_NOTICE\n");
        if (StringUtils.hasText(publicationId)) {
            sb.append("Publication: ").append(publicationId.trim()).append('\n');
        }
        if (StringUtils.hasText(title)) {
            sb.append("Title: ").append(title.trim()).append("\n\n");
        }
        if (StringUtils.hasText(buyerName)) {
            sb.append("Contracting Authority: ").append(buyerName.trim()).append('\n');
        }
        if (StringUtils.hasText(cpvCodes)) {
            sb.append("CPV Codes: ").append(cpvCodes.trim()).append('\n');
        }
        if (StringUtils.hasText(nutsCodes)) {
            sb.append("NUTS Codes: ").append(nutsCodes.trim()).append('\n');
        }
        if (StringUtils.hasText(description)) {
            sb.append("\nDescription: ").append(description.trim()).append("\n\n");
        }
        sb.append(normalizedText.trim());
        return sb.toString().trim();
    }

    private String asString(Object value) {
        return value instanceof String s && StringUtils.hasText(s) ? s : null;
    }
}
