"""
Combat Cleanup Tasks.

This module provides scheduled tasks for cleaning up ended combat
encounters that are older than the retention period.

The cleanup can be scheduled to run periodically (daily recommended)
via APScheduler, cron, or manual invocation.

Usage:
    # Manual invocation
    from app.tasks.combat_cleanup import cleanup_old_combat_encounters
    result = cleanup_old_combat_encounters(older_than_days=7)

    # Via APScheduler
    scheduler.add_job(
        cleanup_old_combat_encounters,
        'interval',
        days=1,
        kwargs={'older_than_days': 7}
    )
"""

from typing import Dict, Any

from app.services.combat_repository import get_combat_repository
from app.utils.logging import get_logger

logger = get_logger(__file__)


# Default retention period in days
DEFAULT_RETENTION_DAYS = 7


def cleanup_old_combat_encounters(
    older_than_days: int = DEFAULT_RETENTION_DAYS
) -> Dict[str, Any]:
    """
    Delete ended combat encounters older than specified days.

    This is the main cleanup function for time-based retention.
    Should be scheduled to run periodically (daily recommended).

    Only deletes ENDED encounters (victory, defeat, fled) - active
    encounters are never deleted.

    Args:
        older_than_days: Number of days after which to delete ended combats.
                        Default is 7 days.

    Returns:
        Dict containing:
        - deleted_encounters: Number of encounters deleted
        - deleted_rounds: Approximate rounds deleted (cascaded)
        - older_than_days: The threshold used
        - success: Whether the operation completed successfully
        - error: Error message if failed

    Example:
        >>> result = cleanup_old_combat_encounters(older_than_days=7)
        >>> print(f"Deleted {result['deleted_encounters']} encounters")
    """
    logger.info("Starting combat encounter cleanup",
               older_than_days=older_than_days)

    try:
        repo = get_combat_repository()
        deleted_count = repo.delete_old_encounters(older_than_days)

        result = {
            "deleted_encounters": deleted_count,
            "older_than_days": older_than_days,
            "success": True,
            "error": None
        }

        logger.info("Combat encounter cleanup completed successfully",
                   deleted_count=deleted_count,
                   older_than_days=older_than_days)

        return result

    except Exception as e:
        logger.error("Combat encounter cleanup failed",
                    error=str(e),
                    older_than_days=older_than_days)

        return {
            "deleted_encounters": 0,
            "older_than_days": older_than_days,
            "success": False,
            "error": str(e)
        }


def cleanup_encounters_for_session(session_id: str) -> Dict[str, Any]:
    """
    Delete all combat encounters for a specific session.

    Call this when a session is being deleted to clean up
    associated combat data.

    Args:
        session_id: The session ID to clean up

    Returns:
        Dict containing:
        - deleted_encounters: Number of encounters deleted
        - session_id: The session ID processed
        - success: Whether the operation completed successfully
        - error: Error message if failed
    """
    logger.info("Cleaning up combat encounters for session",
               session_id=session_id)

    try:
        repo = get_combat_repository()
        deleted_count = repo.delete_encounters_by_session(session_id)

        result = {
            "deleted_encounters": deleted_count,
            "session_id": session_id,
            "success": True,
            "error": None
        }

        logger.info("Session combat cleanup completed",
                   session_id=session_id,
                   deleted_count=deleted_count)

        return result

    except Exception as e:
        logger.error("Session combat cleanup failed",
                    session_id=session_id,
                    error=str(e))

        return {
            "deleted_encounters": 0,
            "session_id": session_id,
            "success": False,
            "error": str(e)
        }
