from django.core.cache import cache
from .ministry_reports_helper import get_preloaded_ministry_data, get_ministry_report_cache_key
from organisations.models import Organisation
import logging

logger = logging.getLogger(__name__)


def warm_ministry_reports_cache(organisation_ids=None):
    """
    Pre-warm the cache for ministry reports
    """
    if organisation_ids is None:
        # Get all organizations
        organisation_ids = list(Organisation.objects.values_list('id', flat=True))
    
    if not isinstance(organisation_ids, list):
        organisation_ids = [organisation_ids]
    
    warmed_count = 0
    failed_count = 0
    
    for org_id in organisation_ids:
        try:
            # Pre-load data for this organization
            data = get_preloaded_ministry_data(org_id)
            if "error" not in data:
                warmed_count += 1
                logger.info(f"Warmed cache for organization {org_id}")
            else:
                failed_count += 1
                logger.warning(f"Failed to warm cache for organization {org_id}: {data.get('error')}")
        except Exception as e:
            failed_count += 1
            logger.error(f"Error warming cache for organization {org_id}: {str(e)}")
    
    return {
        "warmed": warmed_count,
        "failed": failed_count,
        "total": len(organisation_ids)
    }


def get_cache_status(organisation_id):
    """
    Check if ministry report data is cached for an organization
    """
    cache_key = get_ministry_report_cache_key(organisation_id, 'preloaded')
    cached_data = cache.get(cache_key)
    
    return {
        "organisation_id": organisation_id,
        "is_cached": cached_data is not None,
        "cache_key": cache_key,
        "last_updated": cached_data.get("last_updated") if cached_data else None
    }


def clear_ministry_reports_cache(organisation_ids=None):
    """
    Clear ministry reports cache for specified organizations
    """
    if organisation_ids is None:
        organisation_ids = list(Organisation.objects.values_list('id', flat=True))
    
    if not isinstance(organisation_ids, list):
        organisation_ids = [organisation_ids]
    
    cleared_count = 0
    
    for org_id in organisation_ids:
        try:
            cache_keys = [
                get_ministry_report_cache_key(org_id, 'overview'),
                get_ministry_report_cache_key(org_id, 'preloaded')
            ]
            cache.delete_many(cache_keys)
            cleared_count += 1
            logger.info(f"Cleared cache for organization {org_id}")
        except Exception as e:
            logger.error(f"Error clearing cache for organization {org_id}: {str(e)}")
    
    return {
        "cleared": cleared_count,
        "total": len(organisation_ids)
    }