@echo off
setlocal enabledelayedexpansion

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

REM Clean old input and output data (remove and recreate directories)
if exist ..\SRC\MaiML2Excel\DATA\INPUT (
  rmdir /s /q ..\SRC\MaiML2Excel\DATA\INPUT
)
if exist ..\SRC\MaiML2Excel\DATA\OUTPUT (
  rmdir /s /q ..\SRC\MaiML2Excel\DATA\OUTPUT
)
mkdir ..\SRC\MaiML2Excel\DATA\INPUT
mkdir ..\SRC\MaiML2Excel\DATA\OUTPUT

REM Copy new input data files from DATAFILES to SRC
xcopy /Y /Q .\DATAFILES\MaiML2Excel\INPUT\* ..\SRC\MaiML2Excel\DATA\INPUT\

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

if "%MAIML%"=="" (
  echo No .maiml files found in .\DATAFILES\MaiML2Excel\INPUT\
) else (
  echo Selected MaiML file: %MAIML%
)

REM Rewrite input.json with selected MaiML filename using PowerShell
set "INPUT_JSON=..\SRC\MaiML2Excel\DATA\INPUT\input.json"

echo Updating input.json...
copy "!INPUT_JSON!" "!INPUT_JSON!.bak" >nul
echo Set fso = CreateObject("Scripting.FileSystemObject") > update_json.vbs
echo Set file = fso.OpenTextFile("!INPUT_JSON!", 1) >> update_json.vbs
echo content = file.ReadAll >> update_json.vbs
echo file.Close >> update_json.vbs
echo Set regEx = CreateObject("VBScript.RegExp") >> update_json.vbs
echo regEx.Pattern = "(""maiml_file_name""\s*:\s*"")[^""]*("")" >> update_json.vbs
echo regEx.Global = True >> update_json.vbs
echo newContent = regEx.Replace(content, "$1!MaiML!$2") >> update_json.vbs
echo Set file = fso.OpenTextFile("!INPUT_JSON!", 2) >> update_json.vbs
echo file.Write newContent >> update_json.vbs
echo file.Close >> update_json.vbs
echo WScript.Echo "input.json updated successfully" >> update_json.vbs

cscript //nologo update_json.vbs
set "VBS_EXIT_CODE=!errorlevel!"
del update_json.vbs

if !VBS_EXIT_CODE! neq 0 (
    echo ERROR: Failed to update input.json
    pause
    exit /b 1
)

REM Activate virtual environment and run Python script
call ..\SRC\Handson_venv\Scripts\activate.bat
if errorlevel 1 (
  echo Failed to activate virtual environment. Check path: ..\SRC\Handson_venv\Scripts\activate.bat
  goto :end
)

python ..\SRC\MaiML2Excel\maimlinstancetoxl.py -j
if errorlevel 1 (
  echo Python script returned an error.
)

REM Copy output .xlsx files to DATAFILES (only if they exist)
echo Copying ../SRC/MaiML2Excel/DATA/OUTPUT/*.xlsx to ./DATAFILES/MaiML2Excel/OUTPUT/ ...
if exist ..\SRC\MaiML2Excel\DATA\OUTPUT\*.xlsx (
  if not exist .\DATAFILES\MaiML2Excel\OUTPUT mkdir .\DATAFILES\MaiML2Excel\OUTPUT
  xcopy /Y /Q ..\SRC\MaiML2Excel\DATA\OUTPUT\*.xlsx .\DATAFILES\MaiML2Excel\OUTPUT\
) else (
  echo No .xlsx files found in OUTPUT.
)

REM Deactivate virtual environment
call deactivate

:end
echo MaiML to Excel conversion completed.
pause
