import os
import sys
import traceback
from datetime import datetime

# 添加项目根目录到 Python 路径。打包后可通过环境变量覆盖，
# 以适配 Windows dist / Linux AppDir 等不同目录布局。
project_root = os.environ.get("EG_PROJECT_ROOT") or os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, project_root)

# 设置工作目录为项目根目录
os.chdir(project_root)

# 添加 RenderPipeline 到路径（注意路径名称应与实际目录一致）
render_pipeline_path = os.path.join(project_root, "RenderPipeline")
sys.path.insert(0, render_pipeline_path)

# 添加 RenderPipelineFile 路径
render_pipeline_file_path = os.path.join(project_root, "RenderPipelineFile")
sys.path.insert(0, render_pipeline_file_path)

# 添加 icons 目录到路径
icons_path = os.path.join(project_root, "icons")
sys.path.insert(0, icons_path)


def _write_startup_log(message: str) -> None:
    """Write startup diagnostics next to the executable/source root."""
    log_path = os.path.join(project_root, "eg_startup.log")
    with open(log_path, "a", encoding="utf-8") as handle:
        handle.write(f"\n[{datetime.now().isoformat(timespec='seconds')}] {message}\n")

# 现在可以导入并运行主程序
if __name__ == "__main__":
    try:
        args = sys.argv[1:]
        _write_startup_log(f"Launch args: {args}")
        _write_startup_log(f"Working directory: {os.getcwd()}")

        # 将整个列表转换为字符串（包括方括号）
        args_str = ''.join(args)

        from main import MyWorld

        if args:
            app = MyWorld()
            if hasattr(app, 'project_manager'):
                app.project_manager.openProject(args_str)
            app.run()
        else:
            app = MyWorld()
            app.run()
    except Exception:
        _write_startup_log("Unhandled exception during startup:")
        _write_startup_log(traceback.format_exc())
        raise
