@echo off
setlocal EnableExtensions EnableDelayedExpansion
cd /d "%~dp0"

set "OUTPUT_ROOT=%~f1"
if "%~1"=="" set "OUTPUT_ROOT=%~dp0dist"
set "SOURCE_DIR=%~dp0adapters\blender.scene.author@v3"
set "CONTRACT=%~dp0..\software-contracts\blender.scene.author.v3.json"
set "PACKAGE_DIR=!OUTPUT_ROOT!\blender.scene.author@v3"
set "ARCHIVE_PATH=!OUTPUT_ROOT!\blender.scene.author@v3-adapter.zip"

if not exist "%SOURCE_DIR%\adapter.json" goto :failed
if not exist "%SOURCE_DIR%\worker.py" goto :failed
if not exist "%SOURCE_DIR%\blender_worker.py" goto :failed
if not exist "%SOURCE_DIR%\scene_recipe.py" goto :failed
if not exist "%SOURCE_DIR%\rotary_kiln.py" goto :failed
if not exist "%SOURCE_DIR%\requirements.txt" goto :failed
if not exist "%CONTRACT%" goto :failed
where.exe tar.exe >nul 2>&1
if errorlevel 1 goto :failed

if not exist "!OUTPUT_ROOT!" mkdir "!OUTPUT_ROOT!"
if exist "!PACKAGE_DIR!" rmdir /s /q "!PACKAGE_DIR!"
if exist "!ARCHIVE_PATH!" del /f /q "!ARCHIVE_PATH!"
mkdir "!PACKAGE_DIR!"
copy /y "%SOURCE_DIR%\adapter.json" "!PACKAGE_DIR!\adapter.json" >nul
copy /y "%SOURCE_DIR%\worker.py" "!PACKAGE_DIR!\worker.py" >nul
copy /y "%SOURCE_DIR%\blender_worker.py" "!PACKAGE_DIR!\blender_worker.py" >nul
copy /y "%SOURCE_DIR%\scene_recipe.py" "!PACKAGE_DIR!\scene_recipe.py" >nul
copy /y "%SOURCE_DIR%\rotary_kiln.py" "!PACKAGE_DIR!\rotary_kiln.py" >nul
copy /y "%SOURCE_DIR%\requirements.txt" "!PACKAGE_DIR!\requirements.txt" >nul
copy /y "%CONTRACT%" "!PACKAGE_DIR!\blender.scene.author.v3.json" >nul
if errorlevel 1 goto :failed

tar.exe -a -c -f "!ARCHIVE_PATH!" -C "!OUTPUT_ROOT!" "blender.scene.author@v3"
if errorlevel 1 goto :failed
echo [OK] Blender adapter package: !ARCHIVE_PATH!
exit /b 0

:failed
echo [ERR] Blender adapter packaging failed.
exit /b 1
