from .factory import SqlSessionFactory

class MyBatisContainer:
    """
    通用依赖注入与路由容器
    提供一键式的多数据源加载和动态 DAO 路由功能。
    """
    def __init__(self, config_path: str, models_module):
        self.factory = SqlSessionFactory(config_path=config_path, models_module=models_module)
        self.sessions = {}
        
        # 初始化时自动开启所有注册的数据源会话
        for env_id in self.factory.environments.keys():
            self.sessions[env_id] = self.factory.open_session(env_id)

    def get_dao(self, dao_class):
        """核心自动路由逻辑：根据 DAO 接口自动匹配所属的 SqlSession"""
        namespace = dao_class.__name__
        for session in self.sessions.values():
            if session.has_namespace(namespace):
                return session.get_mapper(dao_class)
        raise ValueError(f"装配失败：没有数据库配置挂载 Mapper [{namespace}]")

    def close_all(self):
        """统一释放所有数据源连接"""
        for session in self.sessions.values():
            session.close()