import xml.etree.ElementTree as ET
import os
from .session import SqlSession

class SqlSessionFactory:
    def __init__(self, config_path: str, models_module):
        self.models_module = models_module
        self.environments = {}
        self.default_env = None
        self.base_dir = os.path.dirname(os.path.abspath(config_path))
        self._parse_config(config_path)

    def _parse_config(self, config_path: str):
        tree = ET.parse(config_path)
        root = tree.getroot()
        envs_node = root.find("environments")
        
        if envs_node is not None:
            self.default_env = envs_node.get("default")
            for env_node in envs_node.findall("environment"):
                env_id = env_node.get("id")
                
                # 【新增】解析 dataSource 的 type 属性
                ds_node = env_node.find("dataSource")
                db_type = ds_node.get("type", "sqlite") # 默认为 sqlite
                db_url = ""
                
                for prop in ds_node.findall("property"):
                    if prop.get("name") == "url":
                        db_url = prop.get("value")
                        # 如果是 sqlite，处理相对路径；如果是 pg 等网络数据库，直接保留 DSN
                        if db_type == "sqlite":
                            db_url = os.path.join(self.base_dir, db_url)

                mapper_paths = []
                mappers_node = env_node.find("mappers")
                if mappers_node is not None:
                    for mapper in mappers_node.findall("mapper"):
                        m_path = os.path.join(self.base_dir, mapper.get("resource"))
                        mapper_paths.append(m_path)

                self.environments[env_id] = {
                    "db_type": db_type,   # 保存数据库类型
                    "db_url": db_url,     # 保存连接字符串
                    "mapper_paths": mapper_paths
                }

    def open_session(self, env_id: str) -> SqlSession:
        if env_id not in self.environments:
            raise ValueError(f"未找到环境配置: {env_id}")
        env_config = self.environments[env_id]
        
        # 将 db_type 传入 Session
        return SqlSession(
            db_type=env_config["db_type"], 
            db_url=env_config["db_url"], 
            mapper_paths=env_config["mapper_paths"], 
            models_module=self.models_module
        )