package org.raddatz.familienarchiv.document.transcription;

import org.raddatz.familienarchiv.document.transcription.TranscriptionBlock;
import org.raddatz.familienarchiv.document.transcription.CompletionStatsRow;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;

import java.util.Collection;
import java.util.List;
import java.util.Optional;
import java.util.UUID;

public interface TranscriptionBlockRepository extends JpaRepository<TranscriptionBlock, UUID> {

    @Query(value = """
            SELECT
                b.document_id                                                              AS documentId,
                ROUND(COUNT(*) FILTER (WHERE b.reviewed = true) * 100.0 / COUNT(*))::int  AS completionPercentage
            FROM transcription_blocks b
            WHERE b.document_id IN :documentIds
            GROUP BY b.document_id
            """, nativeQuery = true)
    List<CompletionStatsRow> findCompletionStatsForDocuments(
            @Param("documentIds") Collection<UUID> documentIds);

    List<TranscriptionBlock> findByDocumentIdOrderBySortOrderAsc(UUID documentId);

    Optional<TranscriptionBlock> findByIdAndDocumentId(UUID id, UUID documentId);

    Optional<TranscriptionBlock> findByAnnotationId(UUID annotationId);

    @Query("""
            SELECT DISTINCT b FROM TranscriptionBlock b
            JOIN FETCH b.mentionedPersons
            WHERE b.id IN (
                SELECT bb.id FROM TranscriptionBlock bb JOIN bb.mentionedPersons m WHERE m.personId = :personId
            )
            """)
    List<TranscriptionBlock> findByPersonIdWithMentionsFetched(@Param("personId") UUID personId);

    void deleteByAnnotationId(UUID annotationId);

    int countByDocumentId(UUID documentId);

    boolean existsByDocumentId(UUID documentId);

    @Query("""
            SELECT b FROM TranscriptionBlock b
            JOIN DocumentAnnotation a ON a.id = b.annotationId
            JOIN Document d ON d.id = b.documentId
            WHERE b.reviewed = true
            AND 'KURRENT_RECOGNITION' MEMBER OF d.trainingLabels
            """)
    List<TranscriptionBlock> findEligibleKurrentBlocks();

    @Query("""
            SELECT b FROM TranscriptionBlock b
            JOIN DocumentAnnotation a ON a.id = b.annotationId
            JOIN Document d ON d.id = b.documentId
            WHERE b.source = 'MANUAL'
            AND 'KURRENT_SEGMENTATION' MEMBER OF d.trainingLabels
            """)
    List<TranscriptionBlock> findSegmentationBlocks();

    // Uses 'KURRENT_RECOGNITION' MEMBER OF d.trainingLabels — aligned with findEligibleKurrentBlocks()
    // which already used this form (changed from d.scriptType = 'KURRENT' in the original queries).
    @Query("""
            SELECT COUNT(b) FROM TranscriptionBlock b
            JOIN Document d ON d.id = b.documentId
            WHERE b.source = 'MANUAL'
            AND d.sender.id = :personId
            AND 'KURRENT_RECOGNITION' MEMBER OF d.trainingLabels
            """)
    long countManualKurrentBlocksByPerson(@Param("personId") UUID personId);

    // Uses 'KURRENT_RECOGNITION' MEMBER OF d.trainingLabels — aligned with findEligibleKurrentBlocks()
    // which already used this form (changed from d.scriptType = 'KURRENT' in the original queries).
    @Query("""
            SELECT b FROM TranscriptionBlock b
            JOIN Document d ON d.id = b.documentId
            WHERE b.source = 'MANUAL'
            AND d.sender.id = :personId
            AND 'KURRENT_RECOGNITION' MEMBER OF d.trainingLabels
            """)
    List<TranscriptionBlock> findManualKurrentBlocksByPerson(@Param("personId") UUID personId);
}
