@echo off
setlocal EnableExtensions EnableDelayedExpansion

REM ============================================================================
REM  GenerateMusicAutoList.bat
REM  Scans Music/*.mp3 and generates MusicAutoList.lua
REM  Optional: auto-guess "Artist - Title" from filename; supports overrides and artist map.
REM  Files (optional):
REM    - music_overrides.csv   -> KEY,Label (Label may contain commas)
REM    - artist_map.csv        -> CODE,Artist Full Name
REM ============================================================================

REM If PowerShell script exists, prefer it for better UI/styling
if exist "%~dp0GenerateMusicAutoList.ps1" (
  powershell -NoProfile -ExecutionPolicy Bypass -File "%~dp0GenerateMusicAutoList.ps1"
  exit /b %ERRORLEVEL%
)

title DeadlyBossMods - Epic Music Pack by ZelionGG
color 07
echo.
color 0B
echo ###############################################
echo #                                             #
echo #   DeadlyBossMods - Epic Music Pack by       #
color 0E
echo #   ZelionGG                                  #
color 0B
echo #                                             #
echo ###############################################
color 07
echo.

REM Resolve addon root (this script's folder)
set "ROOT=%~dp0"
set "MUSIC_DIR=%ROOT%Music\custom"
set "OUT_FILE=%ROOT%MusicAutoList.lua"

if not exist "%ROOT%Music" (
  color 0C
  echo [ERROR] Music directory not found: "%ROOT%Music"
  echo Make sure you run this script from inside DBM-EpicMusicPack folder.
  echo.
  color 0F
  echo Press any key to exit...
  color 0C
  pause >nul
  color 07
  exit /b 1
)
if not exist "%MUSIC_DIR%" (
  echo [INFO] Creating custom music directory: "%MUSIC_DIR%"
  mkdir "%MUSIC_DIR%"
)

REM Prompt for auto-guess option
set "AUTOGUESS="
color 0F
set /p AUTOGUESS=Auto guess Artist and Song name? (Y/N): 
if /i "%AUTOGUESS%"=="Y" (set "AUTOGUESS=Y") else (set "AUTOGUESS=N")
color 07

REM No exclusion prompt: only scanning Music\custom to avoid official duplicates by design

REM Default known artist codes mapping (can be overridden by artist_map.csv)
set "MAP_ES=Epic Score"
set "MAP_RSM=Really Slow Motion"
set "MAP_HSM=Hypersonic Music"
set "MAP_MS=Machinimasound"
set "MAP_CAP=Celestial Aeon Project"
set "MAP_2WEI=2WEI"

REM Load artist_map.csv overrides if present (CODE,Artist Full Name)
if exist "%ROOT%artist_map.csv" (
  for /f "usebackq tokens=1,* delims=," %%A in ("%ROOT%artist_map.csv") do (
    set "code=%%~A"
    set "name=%%~B"
    if defined code (
      for /f "tokens=* delims= " %%Z in ("!code!") do set "code=%%Z"
      for /f "tokens=* delims= " %%Z in ("!name!") do set "name=%%Z"
      if defined name set "MAP_!code!=!name!"
    )
  )
)

REM No official keys loading (ignored by scanning only Music\custom)

REM Load music_overrides.csv if present (KEY,Label)
REM We store as env vars OVR_<KEY>=<Label>
set "OVR_COUNT=0"
if exist "%ROOT%music_overrides.csv" (
  for /f "usebackq tokens=1,* delims=," %%A in ("%ROOT%music_overrides.csv") do (
    set "ovrKey=%%~A"
    set "ovrLabel=%%~B"
    if defined ovrKey (
      REM Trim leading spaces
      for /f "tokens=* delims= " %%Z in ("!ovrKey!") do set "ovrKey=%%Z"
      for /f "tokens=* delims= " %%Z in ("!ovrLabel!") do set "ovrLabel=%%Z"
      set "OVR_!ovrKey!=!ovrLabel!"
      set /a OVR_COUNT+=1 >nul 2>&1
    )
  )
)

REM Write header of Lua file
>"%OUT_FILE%" (
  echo -- This file is auto-generated by GenerateMusicAutoList.bat
  echo -- Do not edit manually. Use music_overrides.csv to override labels.
  echo.
  echo EMP_MUSIC_AUTOLIST = {
)

set /a TOTAL=0
set /a USED_OVR=0

REM Iterate over MP3 files sorted by name
for /f "usebackq delims=" %%F in (`dir /b /a-d /on "%MUSIC_DIR%\*.mp3"`) do (
  set "file=%%~nF"
  set "key=!file!"
  set "label="

  REM Check override first
  for /f "tokens=1,* delims==" %%K in ('set OVR_!key! 2^>nul') do (
    set "label=%%L"
  )
  if defined label (
    set /a USED_OVR+=1 >nul 2>&1
  ) else (
    REM No override -> compute label
    set "rest=!key!"
    if /i "!rest:~0,4!"=="EMP_" set "rest=!rest:~4!"

    if /i "!AUTOGUESS!"=="Y" (
      REM Split on first underscore to identify possible artist code
      set "first="
      set "rem="
      for /f "tokens=1,* delims=_" %%a in ("!rest!") do (
        set "first=%%a"
        set "rem=%%b"
      )
      set "artistCode=!first!"
      set "titleRaw=!rem!"
      if not defined titleRaw (
        REM No underscore -> no artist code
        set "titleRaw=!artistCode!"
        set "artistCode="
      )
      set "artist="
      if defined artistCode (
        for /f "tokens=1,* delims==" %%M in ('set MAP_!artistCode! 2^>nul') do set "artist=%%N"
        if not defined artist set "artist=!artistCode!"
      )
      set "title=!titleRaw:_= !"
      if defined artist (
        if defined title (
          set "label=!artist! - !title!"
        ) else (
          set "label=!artist!"
        )
      ) else (
        set "label=!title!"
      )
    ) else (
      REM AUTOGUESS = N -> produce a readable title from the rest of the key
      set "readable=!rest:_= !"
      set "label=!readable!"
    )
  )

  REM Sanitize quotes for Lua string
  set "safeLabel=!label:"='!"

  >>"%OUT_FILE%" echo     ["!key!"] = "!safeLabel!",
  set /a TOTAL+=1 >nul 2>&1
)

>>"%OUT_FILE%" echo }

echo.
color 0A
echo [OK] Generated: "%OUT_FILE%"
echo      Tracks found: %TOTAL%
if defined OVR_COUNT echo      Overrides loaded: %OVR_COUNT% ^(used: %USED_OVR%^) else echo      Overrides loaded: 0
if /i "%AUTOGUESS%"=="Y" (
  echo      Auto-guess: ENABLED
) else (
  echo      Auto-guess: DISABLED
)
echo      Source folder: "%MUSIC_DIR%"
color 07

echo.
color 0F
echo Press any key to exit...
color 07
pause >nul

color 07
endlocal
exit /b 0
