import ast
import sys
sys.path.insert(0, 'd:\\Users\\TermiNexus\\Desktop\\TransPyC')

from lib.Projectrans.DeclarationGenerator import DeclarationGenerator
from lib.includes import t

# 读取 memhub.pyi
with open('d:\\Users\\TermiNexus\\Desktop\\TransPyC\\.transpyc_cache\\f3560b99de458aec.pyi', 'r', encoding='utf-8') as f:
    pyi_content = f.read()

tree = ast.parse(pyi_content)

# 查找 MemBuddy 类
mem_buddy_node = None
mem_manager_node = None
for node in ast.iter_child_nodes(tree):
    if isinstance(node, ast.ClassDef):
        if node.name == 'MemBuddy':
            mem_buddy_node = node
        elif node.name == 'MemManager':
            mem_manager_node = node

print(f"Found MemBuddy: {mem_buddy_node is not None}")
print(f"Found MemManager: {mem_manager_node is not None}")

if mem_buddy_node:
    print(f"\nMemBuddy bases: {[ast.dump(b) for b in mem_buddy_node.bases]}")
    print(f"MemBuddy methods: {[item.name for item in mem_buddy_node.body if isinstance(item, ast.FunctionDef)]}")

if mem_manager_node:
    print(f"\nMemManager methods: {[item.name for item in mem_manager_node.body if isinstance(item, ast.FunctionDef)]}")

# 创建 DeclarationGenerator 实例
decl_gen = DeclarationGenerator(
    struct_names={'MemManager', 'MemBuddy', 'MemPool', 'MemSlab'},
    enum_names=set(),
    module_sha1='f3560b99de458aec',
    struct_sha1_map={'MemManager': 'f3560b99de458aec', 'MemBuddy': 'f3560b99de458aec'},
    class_def_map={'MemManager': mem_manager_node, 'MemBuddy': mem_buddy_node}
)

# 设置 _pyi_tree
decl_gen._pyi_tree = tree

# 构建 _t_alias_map
decl_gen._t_alias_map = {}
for node in ast.iter_child_nodes(tree):
    if isinstance(node, ast.ImportFrom):
        if node.module in ('t', 'c'):
            for alias in node.names:
                name = alias.name
                asname = alias.asname or name
                t_cls = getattr(t, name, None)
                if isinstance(t_cls, type):
                    decl_gen._t_alias_map[asname] = t_cls

# 测试 _is_marker_base
print(f"\n_is_marker_base('MemManager'): {decl_gen._is_marker_base('MemManager')}")

# 测试 _generate_inherited_method_decls
if mem_buddy_node:
    struct_type_name = '%"f3560b99de458aec.MemBuddy"'
    decls = decl_gen._generate_inherited_method_decls(mem_buddy_node, 'MemBuddy', struct_type_name)
    print(f"\nInherited method decls ({len(decls)}):")
    for d in decls:
        print(f"  {d}")
