@echo off
setlocal enabledelayedexpansion

:: =========================
:: Prompt for Origination Folder (required)
:: =========================
:PromptOrigination
set "ORIGINATION_FOLDER="
set /p ORIGINATION_FOLDER=Enter the origination folder path (e.g., P:\Anime\Show): 
if "%ORIGINATION_FOLDER%"=="" (
    echo You must enter a path for the origination folder.
    goto :PromptOrigination
)

:: =========================
:: Set default Processing Folder
:: =========================
set "DEFAULT_PROCESSING_FOLDER=C:\Users\Tyler\Videos\Video Conversion\temp"

:: Prompt for Processing Folder (optional)
set "PROCESSING_FOLDER="
set /p PROCESSING_FOLDER=Enter processing folder path (or press Enter to use "%DEFAULT_PROCESSING_FOLDER%"): 
if "%PROCESSING_FOLDER%"=="" (
    set "PROCESSING_FOLDER=%DEFAULT_PROCESSING_FOLDER%"
)

:: Prompt for Completed Folder (optional)
set "COMPLETED_FOLDER="
set /p COMPLETED_FOLDER=Enter completed folder path (or press Enter to put output back into the original folder): 

:: =========================
:: Resolution choice (default 1080)
:: =========================
:ChooseResolution
set "RES_CHOICE="
set /p RES_CHOICE=Choose resolution (720 or 1080, default=1080): 
if "%RES_CHOICE%"=="" set "RES_CHOICE=1080"

if "%RES_CHOICE%"=="720" (
    set "RES_HEIGHT=720"
) else if "%RES_CHOICE%"=="1080" (
    set "RES_HEIGHT=1080"
) else (
    echo Invalid choice. Please enter 720 or 1080.
    goto :ChooseResolution
)

:: =========================
:: Determine default CQ and filter based on folder type
:: =========================
set "CQ_DEFAULT="
set "FILTER_FLAGS=lanczos"

echo %ORIGINATION_FOLDER% | findstr /i "\\tv\\" >nul
if not errorlevel 1 (
    set "FILTER_FLAGS=bicubic"
    if "%RES_CHOICE%"=="1080" (
        set "CQ_DEFAULT=28"
    ) else (
        set "CQ_DEFAULT=32"
    )
) else (
    REM Defaults for anime
    if "%RES_CHOICE%"=="1080" (
        set "CQ_DEFAULT=32"
    ) else (
        set "CQ_DEFAULT=34"
    )
)

:: =========================
:: CQ choice (user can override)
:: =========================
set "CQ="
set /p CQ=Enter CQ value (default=%CQ_DEFAULT%): 
if "%CQ%"=="" set "CQ=%CQ_DEFAULT%"

:: =========================
:: Confirm the paths
:: =========================
echo.
echo === Using These Paths ===
echo Origination: %ORIGINATION_FOLDER%
echo Processing:  %PROCESSING_FOLDER%
if defined COMPLETED_FOLDER (
    echo Completed:   %COMPLETED_FOLDER%
) else (
    echo Completed:   [Will return to original folder]
)
echo Resolution:   %RES_CHOICE% (Height %RES_HEIGHT%)
echo CRF/CQ:       %CQ%
echo Scaling:      %FILTER_FLAGS%
echo =========================

:: =========================
:: Ensure folders exist
:: =========================
if not exist "%PROCESSING_FOLDER%" mkdir "%PROCESSING_FOLDER%"
if defined COMPLETED_FOLDER (
    if not exist "%COMPLETED_FOLDER%" mkdir "%COMPLETED_FOLDER%"
)

set "SUFFIX= -EHX"

:: =========================
:: Loop through each episode recursively
:: =========================
for /R "%ORIGINATION_FOLDER%" %%F in (*.mkv *.mp4) do (
    REM Skip files that contain "EHX" or "MeGusta"
    echo %%~nxF | findstr /i "EHX MeGusta" >nul
    if errorlevel 1 (
        echo =====================================================
        echo Processing: %%~nxF

        REM Copy episode to processing folder
        copy "%%F" "%PROCESSING_FOLDER%\%%~nxF"
        set "INPUT_FILE=%PROCESSING_FOLDER%\%%~nxF"

        REM Wait briefly to ensure copy finishes
        timeout /t 1 /nobreak >nul

        rem =========================
        rem Detect audio bitrate & bucket to safe values
        rem =========================
        for /f "tokens=1,2,3 delims=," %%A in ('ffprobe -v error -select_streams a:0 -show_entries stream=index,channels,bit_rate -of csv=p=0 "%INPUT_FILE%"') do (
            set "STREAM_INDEX=%%A"
            set "STREAM_CHANNELS=%%B"
            set /a "STREAM_BR=%%C/1000"  rem kbps approx

            if %%B==2 (
                if !STREAM_BR! lss 80 (
                    set "AUDIO_BITRATE=64000"
                ) else if !STREAM_BR! lss 112 (
                    set "AUDIO_BITRATE=96000"
                ) else (
                    set "AUDIO_BITRATE=128000"
                )
                set "AUDIO_CHANNELS=2"
            ) else (
                if !STREAM_BR! lss 176 (
                    set "AUDIO_BITRATE=160000"
                ) else (
                    set "AUDIO_BITRATE=192000"
                )
                set "AUDIO_CHANNELS=6"
            )
        )

        if "%RES_CHOICE%"=="1080" (
            set "SCALE_WIDTH=1920"
            set "SCALE_HEIGHT=1080"
        ) else (
            set "SCALE_WIDTH=1280"
            set "SCALE_HEIGHT=720"
        )

        REM Default to 128k / 2 channels if detection failed
        if "!AUDIO_BITRATE!"=="" set "AUDIO_BITRATE=128000"
        if "!AUDIO_CHANNELS!"=="" set "AUDIO_CHANNELS=2"

        set "LANGUAGE_TAG="
        for /f "tokens=1,* delims==" %%A in ('ffprobe -v error -select_streams a:0 -show_entries stream_tags=language -of default=nokey=1:noprint_wrappers=1 "!INPUT_FILE!"') do (
            set "LANGUAGE_TAG=%%A"
        )

        if "!LANGUAGE_TAG!"=="" (
            set "LANGUAGE_METADATA=-metadata:s:a:0 language=eng"
        ) else (
            set "LANGUAGE_METADATA="
        )

        REM =========================
        REM Run conversion with AV1 NVENC, 10-bit, auto aspect ratio
        REM =========================
        ffmpeg -y -i "!INPUT_FILE!" ^
            -vf "scale=!SCALE_WIDTH!:!SCALE_HEIGHT!:flags=!FILTER_FLAGS!:force_original_aspect_ratio=decrease" ^
            -map 0:v -map 0:a -map 0:s? ^
            -c:v av1_nvenc -preset p1 -cq %CQ% -pix_fmt p010le ^
            -c:a aac -b:a !AUDIO_BITRATE! -ac !AUDIO_CHANNELS! !LANGUAGE_METADATA! -metadata:s:a:0 bit_rate=!AUDIO_BITRATE! ^
            -c:s copy ^
            "%PROCESSING_FOLDER%\%%~nF%SUFFIX%.mkv"

        REM Move converted file to Completed folder or back to original
        if defined COMPLETED_FOLDER (
            move "%PROCESSING_FOLDER%\%%~nF%SUFFIX%.mkv" "%COMPLETED_FOLDER%\%%~nF%SUFFIX%.mkv"
            set "TARGET_PATH=%COMPLETED_FOLDER%\%%~nF%SUFFIX%.mkv"
        ) else (
            move "%PROCESSING_FOLDER%\%%~nF%SUFFIX%.mkv" "%%~dpF%%~nF%SUFFIX%.mkv"
            set "TARGET_PATH=%%~dpF%%~nF%SUFFIX%.mkv"
        )

        echo Moved file to "!TARGET_PATH!"

        REM Confirm conversion succeeded before deleting originals
        if exist "!TARGET_PATH!" (
            echo Conversion confirmed. Deleting original files...
            del "%%F"
            del "!INPUT_FILE!"
            echo Originals deleted.
        ) else (
            echo ERROR: Converted file not found. Skipping deletion of originals.
        )
    ) else (
        echo Skipping: %%~nxF (contains 'EHX' or 'MeGusta')
    )
)

endlocal
pause
