#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
打包功能测试脚本

测试项目管理器的打包功能是否按照Panda3D官方标准正常工作
"""

import sys
import os
import tempfile
import shutil

# 添加项目路径
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from project.project_manager import ProjectManager
from main import MyWorld

def test_packaging():
    """测试打包功能"""
    
    print("=== Panda3D 标准打包功能测试 ===\n")
    
    # 创建临时项目用于测试
    temp_dir = tempfile.mkdtemp(prefix="panda3d_package_test_")
    print(f"创建临时测试项目: {temp_dir}")
    
    try:
        # 设置测试项目结构
        test_project_path = os.path.join(temp_dir, "TestProject")
        scenes_path = os.path.join(test_project_path, "scenes")
        os.makedirs(scenes_path)
        
        # 创建项目管理器（不需要完整的world对象）
        project_manager = ProjectManager(None)
        project_manager.current_project_path = test_project_path
        
        # 创建一个简单的测试场景文件
        scene_file = os.path.join(scenes_path, "scene.bam")
        
        # 创建一个空的BAM文件用于测试
        print("创建测试场景文件...")
        try:
            # 创建一个最小的场景文件
            with open(scene_file, 'wb') as f:
                # 写入一个最小的Panda3D BAM文件头（只是为了测试）
                f.write(b'BAM\x00')  # 最简单的BAM文件标识
            print("✓ 测试场景文件创建成功")
        except Exception as e:
            print(f"✗ 测试场景文件创建失败: {e}")
            return False
        
        # 测试打包文件创建
        build_dir = os.path.join(test_project_path, "build")
        print(f"\n创建打包文件到: {build_dir}")
        
        project_manager._createStandardBuildFiles(build_dir, test_project_path, scene_file)
        
        # 检查生成的文件
        main_py = os.path.join(build_dir, "main.py")
        setup_py = os.path.join(build_dir, "setup.py")
        scene_bam = os.path.join(build_dir, "scene.bam")
        
        success = True
        
        if os.path.exists(main_py):
            print("✓ main.py 创建成功")
            # 检查文件内容
            with open(main_py, 'r', encoding='utf-8') as f:
                content = f.read()
                if "TestProject" in content:
                    print("  - 项目名称正确替换")
                else:
                    print("  ✗ 项目名称替换失败")
                    success = False
        else:
            print("✗ main.py 创建失败")
            success = False
            
        if os.path.exists(setup_py):
            print("✓ setup.py 创建成功")
            # 检查配置内容
            with open(setup_py, 'r', encoding='utf-8') as f:
                content = f.read()
                if "build_apps" in content and "gui_apps" in content:
                    print("  - 包含标准打包配置")
                else:
                    print("  ✗ 缺少标准打包配置")
                    success = False
        else:
            print("✗ setup.py 创建失败")
            success = False
            
        if os.path.exists(scene_bam):
            print("✓ scene.bam 复制成功")
        else:
            print("✗ scene.bam 复制失败")
            success = False
        
        # 显示生成的文件内容概要
        print(f"\n=== 生成的文件概要 ===")
        for filename in os.listdir(build_dir):
            filepath = os.path.join(build_dir, filename)
            size = os.path.getsize(filepath)
            print(f"  {filename}: {size} bytes")
        
        # 检查setup.py的关键配置
        print(f"\n=== setup.py 配置检查 ===")
        if os.path.exists(setup_py):
            with open(setup_py, 'r', encoding='utf-8') as f:
                content = f.read()
                
            checks = [
                ("APP_NAME", "应用程序名称"),
                ("build_apps", "构建应用配置"),
                ("gui_apps", "GUI应用配置"),
                ("include_patterns", "文件包含模式"),
                ("plugins", "Panda3D插件"),
                ("platforms", "目标平台"),
            ]
            
            for check, desc in checks:
                if check in content:
                    print(f"  ✓ {desc} 配置正确")
                else:
                    print(f"  ✗ {desc} 配置缺失")
                    success = False
        
        print(f"\n=== 测试结果 ===")
        if success:
            print("✓ 所有打包文件创建成功！")
            print("✓ 配置符合Panda3D官方标准")
            print("\n可以手动运行以下命令进行实际打包:")
            print(f"  cd {build_dir}")
            print(f"  python setup.py bdist_apps")
            return True
        else:
            print("✗ 打包文件创建存在问题")
            return False
            
    except Exception as e:
        print(f"测试过程中出现错误: {str(e)}")
        import traceback
        traceback.print_exc()
        return False
        
    finally:
        # 清理临时文件
        try:
            shutil.rmtree(temp_dir)
            print(f"\n清理临时文件: {temp_dir}")
        except Exception as e:
            print(f"清理临时文件失败: {str(e)}")

def test_setup_validation():
    """验证setup.py文件的语法正确性"""
    
    print("\n=== setup.py 语法验证 ===")
    
    # 创建临时目录
    temp_dir = tempfile.mkdtemp(prefix="setup_validation_")
    
    try:
        # 创建项目管理器实例（不需要完整的world对象）
        project_manager = ProjectManager(None)
        
        # 生成setup.py文件
        project_manager._createStandardSetupFile(temp_dir, "ValidationTest")
        
        setup_file = os.path.join(temp_dir, "setup.py")
        
        if not os.path.exists(setup_file):
            print("✗ setup.py 文件未生成")
            return False
        
        # 检查Python语法
        print("检查Python语法...")
        try:
            with open(setup_file, 'r', encoding='utf-8') as f:
                code = f.read()
            
            # 编译代码检查语法
            compile(code, setup_file, 'exec')
            print("✓ Python语法正确")
            
        except SyntaxError as e:
            print(f"✗ Python语法错误: {e}")
            return False
        
        print("✓ setup.py 验证通过")
        return True
        
    except Exception as e:
        print(f"验证过程出错: {str(e)}")
        return False
        
    finally:
        try:
            shutil.rmtree(temp_dir)
        except:
            pass

if __name__ == "__main__":
    print("Panda3D 标准打包功能测试\n")
    
    # 运行测试
    test1_result = test_packaging()
    test2_result = test_setup_validation()
    
    print(f"\n=== 最终测试结果 ===")
    print(f"打包文件创建测试: {'通过' if test1_result else '失败'}")
    print(f"setup.py语法验证: {'通过' if test2_result else '失败'}")
    
    if test1_result and test2_result:
        print("\n🎉 所有测试通过！新的打包功能工作正常。")
        print("📦 现在可以使用标准的Panda3D打包流程了。")
    else:
        print("\n❌ 部分测试失败，需要检查配置。") 