#!/usr/bin/env python3
"""
存储工厂类
"""

from typing import Type, Dict
from .base import StorageInterface, StorageConfig, StorageType, StorageException
from .json_storage import JSONStorage
from python_core.utils.logger import logger

class StorageFactory:
    """存储工厂类"""
    
    _storage_classes: Dict[StorageType, Type[StorageInterface]] = {
        StorageType.JSON: JSONStorage,
    }
    
    @classmethod
    def register_storage(cls, storage_type: StorageType, storage_class: Type[StorageInterface]):
        """注册存储实现
        
        Args:
            storage_type: 存储类型
            storage_class: 存储实现类
        """
        cls._storage_classes[storage_type] = storage_class
        logger.info(f"Registered storage type: {storage_type.value}")
    
    @classmethod
    def create_storage(cls, config: StorageConfig) -> StorageInterface:
        """创建存储实例
        
        Args:
            config: 存储配置
            
        Returns:
            StorageInterface: 存储实例
            
        Raises:
            StorageException: 当存储类型不支持时
        """
        storage_type = config.storage_type
        
        if storage_type not in cls._storage_classes:
            available_types = list(cls._storage_classes.keys())
            raise StorageException(
                f"Unsupported storage type: {storage_type.value}. "
                f"Available types: {[t.value for t in available_types]}"
            )
        
        storage_class = cls._storage_classes[storage_type]
        
        try:
            storage = storage_class(config)
            logger.info(f"Created storage instance: {storage_type.value}")
            return storage
        except Exception as e:
            logger.error(f"Failed to create storage instance {storage_type.value}: {e}")
            raise StorageException(f"Failed to create storage: {e}")
    
    @classmethod
    def get_available_types(cls) -> list[StorageType]:
        """获取可用的存储类型
        
        Returns:
            List[StorageType]: 可用的存储类型列表
        """
        return list(cls._storage_classes.keys())
    
    @classmethod
    def create_json_storage(cls, base_path: str = None) -> StorageInterface:
        """创建JSON存储实例（便捷方法）
        
        Args:
            base_path: 存储基础路径
            
        Returns:
            StorageInterface: JSON存储实例
        """
        config = StorageConfig(
            storage_type=StorageType.JSON,
            base_path=base_path
        )
        return cls.create_storage(config)

# 全局存储实例缓存
_storage_instances: Dict[str, StorageInterface] = {}

def get_storage(storage_key: str = "default", config: StorageConfig = None) -> StorageInterface:
    """获取存储实例（单例模式）
    
    Args:
        storage_key: 存储实例键
        config: 存储配置（首次创建时需要）
        
    Returns:
        StorageInterface: 存储实例
        
    Raises:
        StorageException: 当配置缺失时
    """
    if storage_key not in _storage_instances:
        if config is None:
            # 使用默认JSON存储配置
            config = StorageConfig(storage_type=StorageType.JSON)
        
        _storage_instances[storage_key] = StorageFactory.create_storage(config)
    
    return _storage_instances[storage_key]

def close_all_storages():
    """关闭所有存储实例"""
    for storage_key, storage in _storage_instances.items():
        try:
            storage.close()
            logger.info(f"Closed storage instance: {storage_key}")
        except Exception as e:
            logger.error(f"Failed to close storage {storage_key}: {e}")
    
    _storage_instances.clear()

# 注册未来的存储实现
def register_database_storage():
    """注册数据库存储（未来实现）"""
    try:
        from .database_storage import DatabaseStorage
        StorageFactory.register_storage(StorageType.DATABASE, DatabaseStorage)
    except ImportError:
        logger.debug("Database storage not available")

def register_mongodb_storage():
    """注册MongoDB存储（未来实现）"""
    try:
        from .mongodb_storage import MongoDBStorage
        StorageFactory.register_storage(StorageType.MONGODB, MongoDBStorage)
    except ImportError:
        logger.debug("MongoDB storage not available")

def register_redis_storage():
    """注册Redis存储（未来实现）"""
    try:
        from .redis_storage import RedisStorage
        StorageFactory.register_storage(StorageType.REDIS, RedisStorage)
    except ImportError:
        logger.debug("Redis storage not available")

# 自动注册可用的存储类型
def auto_register_storages():
    """自动注册所有可用的存储类型"""
    register_database_storage()
    register_mongodb_storage()
    register_redis_storage()

# 模块加载时自动注册
auto_register_storages()
