@echo off
setlocal enabledelayedexpansion

REM Change current directory to the location of this batch file
cd /d %~dp0

REM Clean old input data
rmdir /s /q ..\SRC\Excel2MaiMLData\INPUT\maiml
rmdir /s /q ..\SRC\Excel2MaiMLData\INPUT\excel
rmdir /s /q ..\SRC\Excel2MaiMLData\INPUT\others

mkdir ..\SRC\Excel2MaiMLData\INPUT\maiml
mkdir ..\SRC\Excel2MaiMLData\INPUT\excel
mkdir ..\SRC\Excel2MaiMLData\INPUT\others

REM Copy new input data files from DATAFILES to SRC
xcopy /Y /Q .\DATAFILES\Excel2MaiMLData\INPUT\excel\*  ..\SRC\Excel2MaiMLData\INPUT\excel\
xcopy /Y /Q .\DATAFILES\Excel2MaiMLData\INPUT\maiml\*  ..\SRC\Excel2MaiMLData\INPUT\maiml\
xcopy /Y /Q .\DATAFILES\Excel2MaiMLData\INPUT\others\* ..\SRC\Excel2MaiMLData\INPUT\others\
xcopy /Y /Q .\DATAFILES\Excel2MaiMLData\INPUT\users\usersettings.py ..\SRC\Excel2MaiMLData\USERS\

REM Get the first Excel filename
set "EXCEL="
for %%f in (.\DATAFILES\Excel2MaiMLData\INPUT\excel\*.xlsx) do (
    set "EXCEL=%%~nxf"
    goto :got_excel
)
:got_excel

REM Get the first MaiML filename
set "MAIML="
for %%f in (.\DATAFILES\Excel2MaiMLData\INPUT\maiml\*.maiml) do (
    set "MAIML=%%~nxf"
    goto :got_maiml
)
:got_maiml

REM Rewrite usersettings.py with the selected filenames (using PowerShell, output UTF-8 to avoid mojibake)
powershell -Command "(Get-Content -Encoding UTF8 '..\SRC\Excel2MaiMLData\USERS\usersettings.py') -replace '(_INPUT_EXCEL_PATH = ).*', '$1\"%EXCEL%\"' -replace '(_INPUT_MaiML_PATH = ).*', '$1\"%MAIML%\"' | Set-Content -Encoding UTF8 '..\SRC\Excel2MaiMLData\USERS\usersettings.py'"

REM Activate Python virtual environment and run the script
call ..\SRC\Handson_venv\Scripts\activate.bat
python ..\SRC\Excel2MaiMLData\excel2dataMaiML2.py

REM Copy output .maiml files to DATAFILES (only if they exist)
echo Copying ../SRC/Excel2MaiMLData/OUTPUT/*.maiml to ./DATAFILES/Excel2MaiMLData/OUTPUT/ ...
if exist ..\SRC\Excel2MaiMLData\OUTPUT\*.maiml (
  xcopy /Y /Q ..\SRC\Excel2MaiMLData\OUTPUT\*.maiml .\DATAFILES\Excel2MaiMLData\OUTPUT\
) else (
  echo No .maiml files found in OUTPUT.
)

REM Deactivate virtual environment
call deactivate

echo completed.
pause
