from typing import Type

from flask import Flask

from common.utils.cache.base import CacheHandler
from common.utils.cache.regions import create_cache_regions
from common.utils.cache.config_cache import AgentConfigCacheHandler


class EveAICacheManager:
    """Cache manager with registration capabilities"""

    def __init__(self):
        self._regions = {}
        self._handlers = {}
        self._handler_instances = {}

    def init_app(self, app: Flask):
        """Initialize cache regions"""
        self._regions = create_cache_regions(app)

        # Store regions in instance
        for region_name, region in self._regions.items():
            setattr(self, f"{region_name}_region", region)

        app.logger.info(f'Cache regions initialized: {self._regions.keys()}')

    def register_handler(self, handler_class: Type[CacheHandler], region: str):
        """Register a cache handler class with its region"""
        if not hasattr(handler_class, 'handler_name'):
            raise ValueError("Cache handler must define handler_name class attribute")
        self._handlers[handler_class] = region

        # Create handler instance
        region_instance = self._regions[region]
        handler_instance = handler_class(region_instance)
        self._handler_instances[handler_class.handler_name] = handler_instance

    def invalidate_region(self, region_name: str):
        """Invalidate an entire cache region"""
        if region_name in self._regions:
            self._regions[region_name].invalidate()
        else:
            raise ValueError(f"Unknown cache region: {region_name}")

    def __getattr__(self, name):
        """Handle dynamic access to registered handlers"""
        instances = object.__getattribute__(self, '_handler_instances')
        if name in instances:
            return instances[name]
        raise AttributeError(f"'EveAICacheManager' object has no attribute '{name}'")
