import time

from redis import Redis

from common.extensions import cache_manager


def perform_startup_actions(app):
    pass
    # perform_startup_invalidation(app)


def perform_startup_invalidation(app):
    """
    Perform cache invalidation only once during startup using a persistent marker (also called flag or semaphore
    - see docs).
    Uses a combination of lock and marker to ensure invalidation happens exactly once
    per deployment.
    """
    redis_client = Redis.from_url(app.config['REDIS_BASE_URI'])
    startup_time = int(time.time())
    marker_key = 'startup_invalidation_completed'
    lock_key = 'startup_invalidation_lock'

    try:
        # First try to get the lock
        lock = redis_client.lock(lock_key, timeout=30)
        if lock.acquire(blocking=False):
            try:
                # Check if invalidation was already performed
                if not redis_client.get(marker_key):
                    # Perform invalidation
                    cache_manager.invalidate_region('eveai_config')
                    cache_manager.invalidate_region('eveai_chat_workers')

                    redis_client.setex(marker_key, 180, str(startup_time))
                    app.logger.info("Startup cache invalidation completed")
                else:
                    app.logger.info("Startup cache invalidation already performed")
            finally:
                lock.release()
        else:
            app.logger.info("Another process is handling startup invalidation")

    except Exception as e:
        app.logger.error(f"Error during startup invalidation: {e}")
        # In case of error, we don't want to block the application startup
        pass

