from typing import get_type_hints

class MapperProxy:
    """动态代理：拦截接口调用并转化为 SQL 执行"""
    def __init__(self, session, dao_class):
        self.session = session
        self.dao_class = dao_class
        self.namespace = dao_class.__name__

    def __getattr__(self, method_name: str):
        if not hasattr(self.dao_class, method_name):
            raise AttributeError(f"[{self.namespace}] 接口中未定义方法: {method_name}")

        statement_id = f"{self.namespace}.{method_name}"
        if statement_id not in self.session.sql_registry:
            raise AttributeError(f"未找到对应的 XML SQL 映射: {statement_id}")

        statement_info = self.session.sql_registry[statement_id]
        sql_type = statement_info["type"]

        method_reference = getattr(self.dao_class, method_name)
        hints = get_type_hints(method_reference)
        return_type_str = str(hints.get('return', ''))
        is_list_return = 'List' in return_type_str or 'list' in return_type_str

        def method_executor(**kwargs):
            if sql_type == "select":
                if is_list_return:
                    return self.session.select_list(statement_id, kwargs)
                else:
                    return self.session.select_one(statement_id, kwargs)
            elif sql_type in ("insert", "update", "delete"):
                return self.session.execute_update(statement_id, kwargs)

        return method_executor