# #region TaskCleanupModule [C:3] [TYPE Module] [SEMANTICS task, logs, task-cleanup-service]
# @BRIEF Implements task cleanup and retention policies, including associated logs.
# @LAYER Core
# @RELATION DEPENDS_ON -> [TaskPersistenceService]
# @RELATION DEPENDS_ON -> [TaskLogPersistenceService]
# @RELATION DEPENDS_ON -> [ConfigManager]

from ..config_manager import ConfigManager
from ..logger import belief_scope, logger
from .persistence import TaskLogPersistenceService, TaskPersistenceService


# #region TaskCleanupService [C:3] [TYPE Class]
# @BRIEF Provides methods to clean up old task records and their associated logs.
# @RELATION DEPENDS_ON -> [TaskPersistenceService]
# @RELATION DEPENDS_ON -> [TaskLogPersistenceService]
# @RELATION DEPENDS_ON -> [ConfigManager]
class TaskCleanupService:
    # #region __init__ [TYPE Function]
    # @PURPOSE: Initializes the cleanup service with dependencies.
    # @PRE      persistence_service and config_manager are valid.
    # @POST     Cleanup service is ready.
    def __init__(
        self,
        persistence_service: TaskPersistenceService,
        log_persistence_service: TaskLogPersistenceService,
        config_manager: ConfigManager
    ):
        self.persistence_service = persistence_service
        self.log_persistence_service = log_persistence_service
        self.config_manager = config_manager
    # #endregion __init__
    # #region run_cleanup [TYPE Function]
    # @PURPOSE: Deletes tasks older than the configured retention period and their logs.
    # @PRE      Config manager has valid settings.
    # @POST     Old tasks and their logs are deleted from persistence.
    def run_cleanup(self):
        with belief_scope("TaskCleanupService.run_cleanup"):
            settings = self.config_manager.get_config().settings
            retention_days = settings.task_retention_days

            logger.info(f"Cleaning up tasks older than {retention_days} days.")

            # Load tasks to check for limit
            tasks = self.persistence_service.load_tasks(limit=1000)
            if len(tasks) > settings.task_retention_limit:
                to_delete: list[str] = [t.id for t in tasks[settings.task_retention_limit:]]

                # Delete logs first (before task records)
                self.log_persistence_service.delete_logs_for_tasks(to_delete)

                # Then delete task records
                self.persistence_service.delete_tasks(to_delete)

                logger.info(f"Deleted {len(to_delete)} tasks and their logs exceeding limit of {settings.task_retention_limit}")
    # #endregion run_cleanup

    # #region delete_task_with_logs [TYPE Function]
    # @PURPOSE: Delete a single task and all its associated logs.
    # @PRE  task_id is a valid task ID.
    # @POST  Task and all its logs are deleted.
    # @PARAM  task_id (str) - The task ID to delete.
    def delete_task_with_logs(self, task_id: str) -> None:
        """Delete a single task and all its associated logs."""
        with belief_scope("TaskCleanupService.delete_task_with_logs", f"task_id={task_id}"):
            # Delete logs first
            self.log_persistence_service.delete_logs_for_task(task_id)

            # Then delete task record
            self.persistence_service.delete_tasks([task_id])

            logger.info(f"Deleted task {task_id} and its associated logs")
    # #endregion delete_task_with_logs
# #endregion TaskCleanupService
# #endregion TaskCleanupModule
