package com.iqser.red.service.persistence.management.v1.processor.service.download;

import java.io.IOException;
import java.util.Collection;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

import jakarta.transaction.Transactional;

import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Service;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.iqser.red.service.pdftron.redaction.v1.api.model.RedactionMessage;
import com.iqser.red.service.pdftron.redaction.v1.api.model.RedactionResultDetail;
import com.iqser.red.service.pdftron.redaction.v1.api.model.RedactionResultMessage;
import com.iqser.red.service.pdftron.redaction.v1.api.model.RedactionType;
import com.iqser.red.service.persistence.management.v1.processor.configuration.MessagingConfiguration;
import com.iqser.red.service.persistence.management.v1.processor.entity.dossier.FileEntity;
import com.iqser.red.service.persistence.management.v1.processor.entity.dossier.ReportTemplateEntity;
import com.iqser.red.service.persistence.management.v1.processor.entity.download.DownloadStatusEntity;
import com.iqser.red.service.persistence.management.v1.processor.service.ColorsService;
import com.iqser.red.service.persistence.management.v1.processor.service.FileManagementStorageService;
import com.iqser.red.service.persistence.management.v1.processor.service.persistence.DossierTemplatePersistenceService;
import com.iqser.red.service.persistence.management.v1.processor.service.persistence.DownloadStatusPersistenceService;
import com.iqser.red.service.persistence.management.v1.processor.service.persistence.FileStatusPersistenceService;
import com.iqser.red.service.persistence.management.v1.processor.service.persistence.NotificationPersistenceService;
import com.iqser.red.service.persistence.management.v1.processor.service.persistence.ReportTemplatePersistenceService;
import com.iqser.red.service.persistence.management.v1.processor.settings.FileManagementServiceSettings;
import com.iqser.red.service.persistence.management.v1.processor.utils.FileSystemBackedArchiver;
import com.iqser.red.service.persistence.service.v1.api.shared.model.audit.AddNotificationRequest;
import com.iqser.red.service.persistence.service.v1.api.shared.model.dossiertemplate.DownloadFileType;
import com.iqser.red.service.persistence.service.v1.api.shared.model.dossiertemplate.dossier.file.FileType;
import com.iqser.red.service.persistence.service.v1.api.shared.model.dossiertemplate.dossier.file.WorkflowStatus;
import com.iqser.red.service.persistence.service.v1.api.shared.model.download.DownloadStatusValue;
import com.iqser.red.service.redaction.report.v1.api.model.ReportResultMessage;
import com.iqser.red.service.redaction.report.v1.api.model.StoredFileInformation;
import com.iqser.red.storage.commons.service.StorageService;
import com.knecon.fforesight.tenantcommons.TenantContext;

import lombok.AccessLevel;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import lombok.experimental.FieldDefaults;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@Service
@RequiredArgsConstructor
@FieldDefaults(level = AccessLevel.PRIVATE, makeFinal = true)
public class DownloadPreparationService {

    DownloadStatusPersistenceService downloadStatusPersistenceService;
    FileStatusPersistenceService fileStatusPersistenceService;
    FileManagementStorageService fileManagementStorageService;
    ReportTemplatePersistenceService reportTemplatePersistenceService;
    NotificationPersistenceService notificationPersistenceService;
    RabbitTemplate rabbitTemplate;
    ObjectMapper objectMapper;
    StorageService storageService;
    DownloadReportCleanupService downloadReportCleanupService;
    ColorsService colorsService;
    FileManagementServiceSettings settings;
    DossierTemplatePersistenceService dossierTemplatePersistenceService;


    @Transactional
    public void createDownload(ReportResultMessage reportResultMessage) throws JsonProcessingException {

        var downloadStatus = downloadStatusPersistenceService.getStatus(reportResultMessage.getDownloadId());
        var dossier = downloadStatus.getDossier();
        var storedPreviewColor = downloadStatus.getRedactionPreviewColor();
        var dossierTemplate = dossierTemplatePersistenceService.getDossierTemplate(dossier.getDossierTemplateId());

        final String previewColor;
        if (storedPreviewColor == null || storedPreviewColor.isBlank()) {
            var colors = colorsService.getColors(dossier.getDossierTemplateId());
            previewColor = colors.getPreviewColor();
        } else {
            previewColor = storedPreviewColor;
        }
        String appliedRedactionColor = colorsService.getColors(dossier.getDossierTemplateId()).getAppliedRedactionColor();

        RedactionMessage message = RedactionMessage.builder()
                .dossierId(dossier.getId())
                .downloadId(reportResultMessage.getDownloadId())
                .redactionTypes(toPdfTronRedactionTypes(downloadStatus.getDownloadFileTypes()))
                .fileIds(downloadStatus.getFiles().stream().map(FileEntity::getId).collect(Collectors.toList()))
                .unapprovedFileIds(downloadStatus.getFiles()
                        .stream()
                        .filter(f -> !WorkflowStatus.APPROVED.equals(f.getWorkflowStatus()))
                        .map(FileEntity::getId)
                        .collect(Collectors.toSet()))
                .redactionPreviewColor(previewColor)
                .keepImageMetaData(dossierTemplate.isKeepImageMetadata())
                .keepHiddenText(dossierTemplate.isKeepHiddenText())
                .keepOverlappingObjects(dossierTemplate.isKeepOverlappingObjects())
                .appliedRedactionColor(appliedRedactionColor)
                .build();

        log.info("Sending redaction request for downloadId:{} to pdftron-redaction-queue", message.getDownloadId());
        rabbitTemplate.convertAndSend(MessagingConfiguration.PDFTRON_QUEUE, message);
    }


    private List<RedactionType> toPdfTronRedactionTypes(Collection<DownloadFileType> downloadFileTypes) {

        var result = new LinkedList<RedactionType>();
        for (var downloadFileType : downloadFileTypes) {
            switch (downloadFileType) {
                case REDACTED:
                    result.add(RedactionType.REDACTED);
                    break;
                case PREVIEW:
                    result.add(RedactionType.PREVIEW);
                    break;
                case DELTA_PREVIEW:
                    result.add(RedactionType.DELTA);
                    break;
                default:
                    // Other types don't need to be passed to pdf-tron
                    break;
            }
        }

        return result;
    }


    public void createDownload(RedactionResultMessage reportResultMessage) {

        DownloadStatusEntity downloadStatus = downloadStatusPersistenceService.getStatus(reportResultMessage.getDownloadId());

        var storedFileInformations = getStoredFileInformation(reportResultMessage.getDownloadId());

        try (FileSystemBackedArchiver fileSystemBackedArchiver = new FileSystemBackedArchiver()) {

            generateAndAddFiles(downloadStatus, reportResultMessage, fileSystemBackedArchiver);
            addReports(reportResultMessage.getDownloadId(), downloadStatus, storedFileInformations, fileSystemBackedArchiver);
            storeZipFile(downloadStatus, fileSystemBackedArchiver);

            updateStatusToReady(downloadStatus, fileSystemBackedArchiver);

            notificationPersistenceService.insertNotification(AddNotificationRequest.builder()
                    .userId(downloadStatus.getUserId())
                    .issuerId(downloadStatus.getUserId())
                    .notificationType("DOWNLOAD_READY")
                    .target(Map.of("userId", downloadStatus.getUserId(), //
                            "dossierId", downloadStatus.getDossier().getId(), //
                            "downloadId", downloadStatus.getStatus()))
                    .build());
        }

        downloadReportCleanupService.deleteTmpReportFiles(storedFileInformations.stream().map(StoredFileInformation::getStorageId).collect(Collectors.toSet()));
        downloadReportCleanupService.deleteTmpReportFiles(reportResultMessage.getRedactionResultDetails()
                .stream()
                .map(RedactionResultDetail::getStorageId)
                .collect(Collectors.toSet()));
    }


    private void updateStatusToReady(DownloadStatusEntity downloadStatus, FileSystemBackedArchiver fileSystemBackedArchiver) {

        downloadStatusPersistenceService.updateStatus(downloadStatus, DownloadStatusValue.READY, fileSystemBackedArchiver.getContentLength());
    }


    private void generateAndAddFiles(DownloadStatusEntity downloadStatus, RedactionResultMessage reportResultMessage, FileSystemBackedArchiver fileSystemBackedArchiver) {

        int i = 1;
        long fileGenerationStart = System.currentTimeMillis();
        for (FileEntity file : downloadStatus.getFiles()) {

            long start = System.currentTimeMillis();
            byte[] original = fileManagementStorageService.getStoredObjectBytes(file.getDossierId(), file.getId(), FileType.ORIGIN);

            var isFileApproved = WorkflowStatus.APPROVED.equals(file.getWorkflowStatus());
            String filename = isFileApproved ? file.getFilename() : "UNAPPROVED_" + file.getFilename();
            for (DownloadFileType downloadFileType : downloadStatus.getDownloadFileTypes()) {

                if (downloadFileType.name().equals(DownloadFileType.ORIGINAL.name())) {
                    fileSystemBackedArchiver.addEntry(new FileSystemBackedArchiver.ArchiveModel("Original", filename, original));
                }
                if (downloadFileType.name().equals(DownloadFileType.PREVIEW.name())) {
                    fileSystemBackedArchiver.addEntry(new FileSystemBackedArchiver.ArchiveModel("Preview", addSuffix(filename, "highlighted"), //
                            getPreview(file.getId(), reportResultMessage.getRedactionResultDetails())));
                }
                if (downloadFileType.name().equals(DownloadFileType.DELTA_PREVIEW.name())) {
                    fileSystemBackedArchiver.addEntry(new FileSystemBackedArchiver.ArchiveModel("Delta Preview", addSuffix(filename, "delta_highlighted"), //
                            getDeltaPreview(file.getId(), reportResultMessage.getRedactionResultDetails())));
                }
                if (downloadFileType.name().equals(DownloadFileType.REDACTED.name()) && isFileApproved) {
                    fileSystemBackedArchiver.addEntry(new FileSystemBackedArchiver.ArchiveModel("Redacted", addSuffix(file.getFilename(), "redacted"), //
                            getRedacted(file.getId(), reportResultMessage.getRedactionResultDetails())));
                }
            }
            log.info("Successfully added file {}/{} for downloadId {}, took {}", i, downloadStatus.getFiles().size(), downloadStatus.getStorageId(), System.currentTimeMillis() - start);
            i++;
        }
        log.info("Successfully added {} files for downloadId {}, took {}", downloadStatus.getFiles().stream().map(FileEntity::getId).toList(), downloadStatus.getStorageId(), System.currentTimeMillis() - fileGenerationStart);
    }


    private byte[] getRedacted(String fileId, List<RedactionResultDetail> redactionResultDetails) {

        return getStoredFileBytes(fileId, redactionResultDetails, RedactionType.REDACTED);
    }


    private byte[] getStoredFileBytes(String fileId, List<RedactionResultDetail> redactionResultDetails, RedactionType redactionType) {

        var redactionResultDetail = redactionResultDetails.stream().filter(rrd -> Objects.equals(fileId, rrd.getFileId()) && rrd.getRedactionType() == redactionType).findFirst();
        if (redactionResultDetail.isPresent()) {
            try (var inputStream = storageService.getObject(TenantContext.getTenantId(), redactionResultDetail.get().getStorageId()).getInputStream()) {
                return inputStream.readAllBytes();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }

        throw new RuntimeException(String.format("Result for file %s of type %s not found", fileId, redactionType));
    }


    private byte[] getDeltaPreview(String fileId, List<RedactionResultDetail> redactionResultDetails) {

        return getStoredFileBytes(fileId, redactionResultDetails, RedactionType.DELTA);
    }


    private byte[] getPreview(String fileId, List<RedactionResultDetail> redactionResultDetails) {

        return getStoredFileBytes(fileId, redactionResultDetails, RedactionType.PREVIEW);
    }


    private void addReports(String downloadId, DownloadStatusEntity downloadStatus, List<StoredFileInformation> storedFileInformations, FileSystemBackedArchiver fileSystemBackedArchiver) {

        long addReportsStart = System.currentTimeMillis();

        Map<String, FileEntity> fileById = downloadStatus.getFiles().stream().collect(Collectors.toMap(FileEntity::getId, a -> a));

        for (StoredFileInformation storedFileInformation : storedFileInformations) {

            FileEntity fileStatus = null;

            if (storedFileInformation.getFileId() != null) {
                fileStatus = fileById.get(storedFileInformation.getFileId());
            }

            ReportTemplateEntity reportTemplate = reportTemplatePersistenceService.find(storedFileInformation.getTemplateId());
            byte[] report = fileManagementStorageService.getStoredObjectBytes(storedFileInformation.getStorageId());
            fileSystemBackedArchiver.addEntry(new FileSystemBackedArchiver.ArchiveModel(removeExtension(reportTemplate.getFileName()) + (reportTemplate.isMultiFileReport() ? " (multifile)" : ""),
                    settings.isScmEnabled() ? createFileName(fileStatus, reportTemplate) : addSuffix(createFileName(fileStatus, reportTemplate),
                            "justification" + (storedFileInformation.getDocumentPartNr() != 0 ? "_" + storedFileInformation.getDocumentPartNr() : "")),
                    report));

        }
        log.info("Successfully added {} reports for downloadId {}, took {}", storedFileInformations.size(), downloadId, System.currentTimeMillis() - addReportsStart);
    }


    @SneakyThrows
    private List<StoredFileInformation> getStoredFileInformation(String downloadId) {

        var storageId = downloadId.substring(0, downloadId.length() - 3) + "/REPORT_INFO.json";

        return objectMapper.readValue(fileManagementStorageService.getStoredObjectBytes(storageId), new TypeReference<>() {
        });
    }


    private String createFileName(FileEntity fileStatus, ReportTemplateEntity reportTemplate) {

        if (fileStatus != null) {
            var isFileApproved = WorkflowStatus.APPROVED.equals(fileStatus.getWorkflowStatus());
            String filename = isFileApproved ? fileStatus.getFilename() : "UNAPPROVED_" + fileStatus.getFilename();
            return removeExtension(filename) + getExtension(reportTemplate.getFileName());
        } else {
            return reportTemplate.getFileName();
        }
    }


    private String getExtension(String fileName) {

        var index = fileName.lastIndexOf(".");
        if (index > 0) {
            return fileName.substring(index);
        } else {
            return "";
        }
    }


    private String removeExtension(String fileName) {

        var index = fileName.lastIndexOf(".");
        if (index > 0) {
            return fileName.substring(0, index);
        } else {
            return fileName;
        }
    }


    private String addSuffix(String filename, String suffix) {

        var oldExtension = getExtension(filename);
        return removeExtension(filename) + "_" + suffix + oldExtension;

    }


    private void storeZipFile(DownloadStatusEntity downloadStatus, FileSystemBackedArchiver fileSystemBackedArchiver) {

        long start = System.currentTimeMillis();
        fileManagementStorageService.storeObject(downloadStatus.getStorageId(), fileSystemBackedArchiver.toInputStream());
        log.info("Successfully stored zip for downloadId {}, took {}", downloadStatus.getStorageId(), System.currentTimeMillis() - start);
    }

}
