#!/usr/bin/env python3
"""
build_engines.py — 跨平台一键编译所有引擎。

用法:
    py -3 build_engines.py              # 本地编译
    py -3 build_engines.py --target c   # 只编译 C 引擎
    py -3 build_engines.py --release    # Release 模式
    py -3 build_engines.py --clean      # 清理构建目录

依赖: cmake (>= 3.15)
"""

import argparse
import os
import subprocess
import sys
import platform

SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
BUILD_DIR  = os.path.join(SCRIPT_DIR, "build")

def run(cmd, **kwargs):
    print(f"[build] {' '.join(cmd)}")
    result = subprocess.run(cmd, cwd=SCRIPT_DIR, **kwargs)
    if result.returncode != 0:
        sys.exit(result.returncode)
    return result

def main():
    parser = argparse.ArgumentParser(description="一键编译 Dynamics 引擎")
    parser.add_argument("--target", "-t", default="all-engines",
                        help="编译目标: dynamics_c, dynamics_cpp, dynamics_f90, all-engines (默认)")
    parser.add_argument("--release", action="store_true", help="Release 模式")
    parser.add_argument("--debug", action="store_true", help="Debug 模式")
    parser.add_argument("--clean", action="store_true", help="清理后重新编译")
    parser.add_argument("--toolchain", help="交叉编译工具链文件路径")
    args = parser.parse_args()

    # 检查 cmake
    try:
        subprocess.run(["cmake", "--version"], capture_output=True, check=True)
    except (FileNotFoundError, subprocess.CalledProcessError):
        print("[build] 错误: 未找到 cmake，请先安装:")
        system = platform.system().lower()
        if system == "windows":
            print("  下载安装: https://cmake.org/download/")
            print("  或: winget install Kitware.CMake")
        elif system == "darwin":
            print("  brew install cmake")
        else:
            print("  apt install cmake  # Ubuntu/Debian")
            print("  dnf install cmake  # Fedora")
        sys.exit(1)

    # 确定构建类型
    if args.debug:
        build_type = "Debug"
    elif args.release:
        build_type = "Release"
    else:
        build_type = "Release"

    # 清理
    if args.clean and os.path.exists(BUILD_DIR):
        import shutil
        shutil.rmtree(BUILD_DIR)
        print(f"[build] 已清理: {BUILD_DIR}")

    # cmake 配置
    config_cmd = ["cmake", "-B", BUILD_DIR,
                  f"-DCMAKE_BUILD_TYPE={build_type}"]
    if args.toolchain:
        config_cmd.append(f"-DCMAKE_TOOLCHAIN_FILE={args.toolchain}")

    # 并行编译
    nproc = os.cpu_count() or 4
    build_cmd = ["cmake", "--build", BUILD_DIR,
                 "--target", args.target,
                 "--parallel", str(nproc)]

    # 执行
    print(f"[build] 目标: {args.target}")
    print(f"[build] 模式: {build_type}")
    print(f"[build] 系统: {platform.system()} {platform.machine()}")
    run(config_cmd)
    run(build_cmd)

    print(f"\n[build] 完成!")
    print(f"[build] 可执行文件位置: engines/*/build/")

if __name__ == "__main__":
    main()
