"""Casos de uso de lectura y serialización del flujo batch."""

from __future__ import annotations

from dataclasses import dataclass
from typing import Any

from app.batch_processing.application.models import (
    BatchCaseView,
    BatchFileView,
    BatchStatusView,
    UserBatchSummaryView,
)
from app.batch_processing.domain.ports import (
    BatchCaseRepository,
    BatchFileRepository,
    BatchRepository,
)
from app.batch_processing.application.command_use_cases import RecomputeBatchBulkEpicrisisUseCase


@dataclass
class GetBatchStatusUseCase:
    """Expone el resumen agregado del lote con un contrato estable para la UI."""

    batch_repository: BatchRepository
    recompute_bulk_epicrisis_use_case: RecomputeBatchBulkEpicrisisUseCase | None = None

    def execute(self, batch_id: str) -> dict[str, Any] | None:
        if self.recompute_bulk_epicrisis_use_case:
            self.recompute_bulk_epicrisis_use_case.execute(batch_id)
        batch = self.batch_repository.get_batch(batch_id)
        if not batch:
            return None
        return BatchStatusView.from_record(batch).to_document()


@dataclass
class ListUserBatchesUseCase:
    """Devuelve el historial resumido de lotes del usuario autenticado."""

    batch_repository: BatchRepository

    def execute(self, username: str, *, limit: int = 20) -> list[dict[str, Any]]:
        batches = self.batch_repository.list_user_batches(username, limit=limit)
        return [UserBatchSummaryView.from_record(item).to_document() for item in batches]


@dataclass
class ListBatchFilesUseCase:
    """Lista el detalle serializado de archivos visibles en el seguimiento del lote."""

    batch_file_repository: BatchFileRepository

    def execute(self, batch_id: str) -> list[dict[str, Any]]:
        files = self.batch_file_repository.list_files(batch_id)
        return [self.serialize(item) for item in files]

    @staticmethod
    def serialize(item: dict[str, Any]) -> dict[str, Any]:
        """Convierte el documento batch por archivo al formato que consume la UI."""

        return BatchFileView.from_record(item).to_document()


@dataclass
class ListPendingAssociationsUseCase:
    """Lista únicamente los archivos que requieren validación manual."""

    batch_file_repository: BatchFileRepository

    def execute(self, batch_id: str) -> list[dict[str, Any]]:
        files = self.batch_file_repository.list_files(
            batch_id,
            status="pendiente_validacion",
        )
        return [ListBatchFilesUseCase.serialize(item) for item in files]


@dataclass
class ListBatchCasesUseCase:
    """Expone el catálogo serializado de casos consolidados del lote."""

    batch_case_repository: BatchCaseRepository

    def execute(self, batch_id: str) -> list[dict[str, Any]]:
        cases = self.batch_case_repository.list_cases(batch_id)
        return [BatchCaseView.from_record(item).to_document() for item in cases]
