package org.raddatz.familienarchiv.document.transcription;

import lombok.RequiredArgsConstructor;
import org.raddatz.familienarchiv.audit.ActivityActorDTO;
import org.raddatz.familienarchiv.audit.AuditLogQueryService;
import org.raddatz.familienarchiv.document.DocumentService;
import org.raddatz.familienarchiv.document.transcription.TranscriptionQueueItemDTO;
import org.raddatz.familienarchiv.document.transcription.TranscriptionWeeklyStatsDTO;
import org.raddatz.familienarchiv.document.transcription.TranscriptionQueueProjection;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.UUID;

@Service
@RequiredArgsConstructor
public class TranscriptionQueueService {

    private static final int DEFAULT_QUEUE_SIZE = 5;
    private static final int MAX_CONTRIBUTORS = 5;

    private final DocumentService documentService;
    private final AuditLogQueryService auditLogQueryService;

    public List<TranscriptionQueueItemDTO> getSegmentationQueue() {
        return enrichWithContributors(documentService.findSegmentationQueue(DEFAULT_QUEUE_SIZE));
    }

    public List<TranscriptionQueueItemDTO> getTranscriptionQueue() {
        return enrichWithContributors(documentService.findTranscriptionQueue(DEFAULT_QUEUE_SIZE));
    }

    public List<TranscriptionQueueItemDTO> getReadyToReadQueue() {
        return enrichWithContributors(documentService.findReadyToReadQueue(DEFAULT_QUEUE_SIZE));
    }

    public TranscriptionWeeklyStatsDTO getWeeklyStats() {
        var stats = documentService.findWeeklyStats();
        return new TranscriptionWeeklyStatsDTO(
                stats.getSegmentationCount(),
                stats.getTranscriptionCount()
        );
    }

    private List<TranscriptionQueueItemDTO> enrichWithContributors(List<TranscriptionQueueProjection> projections) {
        if (projections.isEmpty()) return List.of();
        List<UUID> ids = projections.stream().map(TranscriptionQueueProjection::getId).toList();
        Map<UUID, List<ActivityActorDTO>> contributorMap = auditLogQueryService.findContributorsPerDocument(ids);
        return projections.stream()
                .map(p -> toDTO(p, contributorMap.getOrDefault(p.getId(), List.of())))
                .toList();
    }

    private TranscriptionQueueItemDTO toDTO(TranscriptionQueueProjection p, List<ActivityActorDTO> allContributors) {
        boolean hasMore = allContributors.size() > MAX_CONTRIBUTORS;
        List<ActivityActorDTO> capped = hasMore ? allContributors.subList(0, MAX_CONTRIBUTORS) : allContributors;
        return new TranscriptionQueueItemDTO(
                p.getId(),
                p.getTitle(),
                p.getDocumentDate(),
                p.getAnnotationCount(),
                p.getTextedBlockCount(),
                p.getReviewedBlockCount(),
                capped,
                hasMore
        );
    }
}
