@echo off
setlocal EnableExtensions EnableDelayedExpansion

:: UpgradeToGitProj.bat
:: Run this inside an existing (pre-git) project root.
:: - Merges .gitignore and .gitattributes from components/ templates
:: - Initializes git and installs Git LFS
:: - Creates Renders, copies helper scripts
:: - Collects seq/ outputs from daily_* folders under Blends\animations (with submodule support)

:: -----------------------------
:: Arguments
:: -----------------------------
set "DRY=0"
if /I "%~1"=="/dry-run" set "DRY=1"
if /I "%~1"=="--dry-run" set "DRY=1"
if /I "%~1"=="-n" set "DRY=1"
if /I "%~1"=="/n" set "DRY=1"

set "projectDir=%CD%"
set "scriptDir=%~dp0"
set "RUN_ID=%RANDOM%_%RANDOM%"
set "DELETE_LIST=%TEMP%\upg_delete_%RUN_ID%.lst"

setlocal EnableDelayedExpansion
set /a debugTotal=0
set /a debugPlanned=0
set /a debugMissing=0

echo ==============================================
echo UpgradeToGitProj in "%projectDir%"
if "%DRY%"=="1" (echo Mode: DRY-RUN) else (echo Mode: APPLY)
echo ==============================================

:: -----------------------------
:: Ensure Renders exists and copy helper scripts
:: -----------------------------
set "rendersDir=%projectDir%\Renders"
if not exist "%rendersDir%" (
  if "%DRY%"=="1" (
    echo [DRY] mkdir "%rendersDir%"
  ) else (
    mkdir "%rendersDir%" >nul 2>&1
  )
)

for %%F in (UpdateSequences.bat ZipSeqArchv.bat UnzipSeqArchv.bat) do (
  if exist "%scriptDir%%%F" (
    if "%DRY%"=="1" (
      echo [DRY] copy "%scriptDir%%%F" "%rendersDir%\%%F"
    ) else (
      copy /Y "%scriptDir%%%F" "%rendersDir%\%%F" >nul
    )
  ) else (
    echo [WARN] Missing template: "%scriptDir%%%F"
  )
)

for %%F in (CfgDeploy.ps1 config.json) do (
  if exist "%scriptDir%%%F" (
    if "%DRY%"=="1" (
      echo [DRY] copy "%scriptDir%%%F" "%rendersDir%\%%F"
    ) else (
      copy /Y "%scriptDir%%%F" "%rendersDir%\%%F" >nul
    )
  ) else (
    echo [WARN] Missing template: "%scriptDir%%%F"
  )
)

:: -----------------------------
:: Merge .gitignore and .gitattributes from templates
:: -----------------------------
set "tplGitIgnore=%scriptDir%components\gitignore"
set "dstGitIgnore=%projectDir%\.gitignore"
set "tplGitAttr=%scriptDir%components\gitattributes"
set "dstGitAttr=%projectDir%\.gitattributes"

call :MergeTemplate "%tplGitIgnore%" "%dstGitIgnore%"
call :MergeTemplate "%tplGitAttr%"   "%dstGitAttr%"

:: -----------------------------
:: Initialize git and Git LFS
:: -----------------------------
if not exist "%projectDir%\.git" (
  if "%DRY%"=="1" (
    echo [DRY] git init
  ) else (
    pushd "%projectDir%" >nul
    git init
    popd >nul
  )
)

if "%DRY%"=="1" (
  echo [DRY] git lfs install
) else (
  pushd "%projectDir%" >nul
  git lfs install
  popd >nul
)

:: -----------------------------
:: Collect seq outputs from daily_* into Renders
:: -----------------------------
set "animDir=%projectDir%\Blends\animations"
set "foundAny=0"
set "foundSubmodules=0"

if exist "%animDir%" (
  if "%DRY%"=="1" echo [DRY] Scanning animations dir: "%animDir%"
  :: Detect submodules: first-level folders under animations that contain daily_*
  for /d %%S in ("%animDir%\*") do (
    set "name=%%~nS"
    set "prefix=!name:~0,6!"
    if /I not "!prefix!"=="daily_" (
      for /d %%D in ("%%S\daily_*") do (
        set "foundSubmodules=1"
      )
      if "%DRY%"=="1" (
        if exist "%%S\daily_*" echo [DRY] Detected submodule: "%%~nS"
      )
    )
  )

  if "!foundSubmodules!"=="1" (
    if "%DRY%"=="1" echo [DRY] Using submodules under Blends\animations
    for /d %%S in ("%animDir%\*") do (
      set "name=%%~nS"
      set "prefix=!name:~0,6!"
      if /I not "!prefix!"=="daily_" (
        set "submodName=%%~nS"
        set "_subdir=%rendersDir%\!submodName!"
        rem Ensure submodule dir exists and place helper scripts there
        if "%DRY%"=="1" (
          if not exist "!_subdir!" echo [DRY] mkdir "!_subdir!"
          if exist "%scriptDir%UpdateSequences.bat" echo [DRY] copy "%scriptDir%UpdateSequences.bat" "!_subdir!\UpdateSequences.bat"
          if exist "%scriptDir%ZipSeqArchv.bat" echo [DRY] copy "%scriptDir%ZipSeqArchv.bat" "!_subdir!\ZipSeqArchv.bat"
          if exist "%scriptDir%UnzipSeqArchv.bat" echo [DRY] copy "%scriptDir%UnzipSeqArchv.bat" "!_subdir!\UnzipSeqArchv.bat"
        ) else (
          if not exist "!_subdir!" mkdir "!_subdir!" >nul 2>&1
          if exist "%scriptDir%UpdateSequences.bat" copy /Y "%scriptDir%UpdateSequences.bat" "!_subdir!\UpdateSequences.bat" >nul
          if exist "%scriptDir%ZipSeqArchv.bat" copy /Y "%scriptDir%ZipSeqArchv.bat" "!_subdir!\ZipSeqArchv.bat" >nul
          if exist "%scriptDir%UnzipSeqArchv.bat" copy /Y "%scriptDir%UnzipSeqArchv.bat" "!_subdir!\UnzipSeqArchv.bat" >nul
        )
        for /d %%D in ("%%S\daily_*") do (
          set "dailyName=%%~nD"
          set "_src=%%D\seq"
          set "_dst=%rendersDir%\!submodName!\!dailyName!"
          set /a debugTotal+=1
          if "%DRY%"=="1" (
            if exist "!_src!" (
              echo [DRY] WOULD copy "!_src!" -^> "!_dst!"
              set /a debugPlanned+=1
            ) else (
              echo [DRY] Skip: missing "!_src!"
              set /a debugMissing+=1
            )
          )
          call :CopySeqToRenders "!_src!" "!_dst!"
        )
      )
    )
    set "foundAny=1"
  ) else (
    if "%DRY%"=="1" echo [DRY] No submodules found; using direct daily_* under animations
    :: Fallback: direct daily_* under animations → copy into Renders\daily_*
    for /d %%D in ("%animDir%\daily_*") do (
      set "_dname=%%~nD"
      set "_src=%%D\seq"
      set "_dst=%rendersDir%\!_dname!"
      set /a debugTotal+=1
      if "%DRY%"=="1" (
        if exist "!_src!" (
          echo [DRY] WOULD copy "!_src!" -^> "!_dst!"
          set /a debugPlanned+=1
        ) else (
          echo [DRY] Skip: missing "!_src!"
          set /a debugMissing+=1
        )
      )
      call :CopySeqToRenders "!_src!" "!_dst!"
      set "foundAny=1"
    )
  )
)

if "!foundAny!"=="0" (
  if "%DRY%"=="1" echo [DRY] Animations dir missing or empty; checking root daily_*
  :: Final fallback: root-level daily_* under projectDir → copy into Renders\daily_*
  for /d %%D in ("%projectDir%\daily_*") do (
    set "_dname=%%~nD"
    set "_src=%%D\seq"
    set "_dst=%rendersDir%\!_dname!"
    set /a debugTotal+=1
    if "%DRY%"=="1" (
      if exist "!_src!" (
        echo [DRY] WOULD copy "!_src!" -^> "!_dst!"
        set /a debugPlanned+=1
      ) else (
        echo [DRY] Skip: missing "!_src!"
        set /a debugMissing+=1
      )
    )
    call :CopySeqToRenders "!_src!" "!_dst!"
    set "foundAny=1"
  )
)

:AfterCopy
if "%DRY%"=="1" (
  echo [DRY] Summary: total dailies=!debugTotal!, with seq=!debugPlanned!, missing=!debugMissing!
  if exist "%DELETE_LIST%" (
    echo [DRY] Would offer to delete these seq folders after copy:
    for /f "usebackq delims=" %%P in ("%DELETE_LIST%") do echo   [DRY] %%P
    del "%DELETE_LIST%" >nul 2>&1
  )
) else (
  if exist "%DELETE_LIST%" (
    echo.
    echo Cleanup option: Remove original seq folders that were copied?
    choice /C YN /N /M "Delete original seq folders now? (Y/N): "
    if errorlevel 2 (
      echo Skipping deletion of original seq folders.
    ) else (
      for /f "usebackq delims=" %%P in ("%DELETE_LIST%") do (
        echo Deleting seq folder: "%%P"
        rd /S /Q "%%P" 2>nul
      )
      echo Cleanup complete.
    )
    del "%DELETE_LIST%" >nul 2>&1
  )
)
echo Done.
exit /b 0

:: ---------------------------------
:: MergeTemplate: copy if missing; else append only missing lines
:: %1 = templatePath, %2 = destinationPath
:: ---------------------------------
:MergeTemplate
setlocal
set "tpl=%~1"
set "dst=%~2"

if not exist "%tpl%" (
  echo [WARN] Template missing: "%tpl%"
  endlocal & exit /b 0
)

if not exist "%dst%" (
  if "%DRY%"=="1" (
    echo [DRY] copy "%tpl%" "%dst%"
  ) else (
    copy /Y "%tpl%" "%dst%" >nul
  )
) else (
  if "%DRY%"=="1" (
    echo [DRY] merge missing lines from "%tpl%" into "%dst%"
  ) else (
    for /f "usebackq delims=" %%L in ("%tpl%") do (
      >nul 2>&1 findstr /x /c:"%%L" "%dst%" || (>>"%dst%" echo %%L)
    )
  )
)

endlocal & exit /b 0

:: ---------------------------------
:: CopySeqToRenders: copies contents of src seq dir into dest
:: %1 = srcSeqDir, %2 = destDir
:: ---------------------------------
:CopySeqToRenders
setlocal EnableExtensions EnableDelayedExpansion
set "src=%~1"
set "dst=%~2"

if "%DRY%"=="1" (
  if not exist "%src%" endlocal & exit /b 0
  if not exist "%dst%" echo [DRY] mkdir "%dst%"
  >> "%DELETE_LIST%" echo %src%
  endlocal & exit /b 0
)

if not exist "%src%" (
  echo [INFO] Skip: missing seq folder "%src%"
  endlocal & exit /b 0
)

if not exist "%dst%" mkdir "%dst%" >nul 2>&1

set "ROBO_OPTS=/E /XO /XN /XC /R:1 /W:1 /NFL /NDL /NP /NJH /NJS"
echo Copy seq: "%src%" -> "%dst%"
robocopy "%src%" "%dst%" * %ROBO_OPTS% >nul
set "__rc=%ERRORLEVEL%"
if not "%__rc%"=="" (
  if %__rc% LSS 8 (
    >> "%DELETE_LIST%" echo %src%
  )
)

endlocal & exit /b 0


