@echo off
chcp 65001 >nul
cls

set "REPO_DIR=%~dp0"
pushd "%REPO_DIR%"

set "YOLO_LAUNCHER="
where yolo >nul 2>nul
if %ERRORLEVEL% equ 0 set "YOLO_LAUNCHER=yolo"

if not defined YOLO_LAUNCHER (
    py -3.11 -c "import ultralytics" >nul 2>nul
    if %ERRORLEVEL% equ 0 set "YOLO_LAUNCHER=py -3.11 -m ultralytics"
)

if not defined YOLO_LAUNCHER (
    python -c "import ultralytics" >nul 2>nul
    if %ERRORLEVEL% equ 0 set "YOLO_LAUNCHER=python -m ultralytics"
)

if not defined YOLO_LAUNCHER (
    echo [错误] 未找到可用的 Ultralytics 启动方式
    echo.
    echo 请先确保满足以下任一条件:
    echo   1. yolo 命令已加入 PATH
    echo   2. py -3.11 可运行并已安装 ultralytics
    echo   3. python 可运行并已安装 ultralytics
    popd
    pause
    exit /b 1
)

echo ============================================================
echo         导出 ONNX 模型 (640x640)
echo ============================================================
echo.

set "MODEL_PATH=%REPO_DIR%runs\detect\train\weights\best.pt"

if not exist "%MODEL_PATH%" (
    echo [错误] 找不到模型: %MODEL_PATH%
    echo 请先运行 02_train.bat 训练
    popd
    pause
    exit /b 1
)

echo [信息] 输入模型: %MODEL_PATH%
echo.

call %YOLO_LAUNCHER% export model="%MODEL_PATH%" format=onnx imgsz=640 opset=12 simplify

if %ERRORLEVEL% neq 0 (
    echo [错误] 导出失败！
    popd
    pause
    exit /b 1
)

echo.
echo [成功] ONNX 模型: %REPO_DIR%runs\detect\train\weights\best.onnx
echo.
echo 下一步: 在 Ubuntu 上运行 04_convert_rknn.py 转换
echo.
popd
pause
