@echo off
title YouTube Downloader with Trim (Live Stream Support)
setlocal EnableDelayedExpansion

:: Create necessary folders
if not exist "video" mkdir "video"
if not exist "audio" mkdir "audio"
if not exist "trim" mkdir "trim"

:: Request YouTube URL
set /p URL=Enter YouTube URL: 

:: Validate YouTube URL
echo "!URL!" | findstr /C:"youtube.com" >nul 2>&1 || (
    echo [ERROR] Invalid YouTube URL.
    pause
    exit /b
)

set "URL_SAFE=%URL:&=^&%"

:: Check for playlists
echo "!URL_SAFE!" | findstr /C:"list=" >nul 2>&1
if !ERRORLEVEL! EQU 0 (
    echo [ERROR] Playlists are not supported.
    pause
    exit /b
)

:: Check for live streams
set "IS_LIVE=0"
yt-dlp.exe --get-duration "!URL_SAFE!" 2>nul | findstr /C:"LIVE" >nul && set "IS_LIVE=1"

if "!IS_LIVE!"=="1" (
    echo [INFO] Live stream detected! The entire stream will be downloaded.
)

echo [INFO] Processing YouTube URL...

:: Choose format
echo.
echo [INFO] Available download options:
echo [0] MP3 (Audio)
echo [1] 480p (MP4)
echo [2] 720p (MP4)
echo [3] 1080p (MP4)
echo [4] Maximum (MP4)
set /p RESOLUTION=Enter option number (0-4): 

if "!RESOLUTION!"=="" (
    echo [ERROR] No option selected.
    pause
    exit /b
)

if "!RESOLUTION!"=="0" goto setAudio
if "!RESOLUTION!"=="1" goto set480p
if "!RESOLUTION!"=="2" goto set720p
if "!RESOLUTION!"=="3" goto set1080p
if "!RESOLUTION!"=="4" goto setMax
echo [ERROR] Invalid selection.
pause
exit /b

:setAudio
    set "FORMAT=140"
    set "OUTPUT_FOLDER=audio"
    set "AUDIO_OPTIONS=-x --audio-format mp3 --audio-quality 320K"
    goto afterRes

:set480p
    set "FORMAT=bestvideo[height<=480][ext=mp4]+bestaudio[ext=m4a]/best[height<=480][ext=mp4]"
    set "OUTPUT_FOLDER=video"
    goto afterRes

:set720p
    set "FORMAT=bestvideo[height<=720][ext=mp4]+bestaudio[ext=m4a]/best[height<=720][ext=mp4]"
    set "OUTPUT_FOLDER=video"
    goto afterRes

:set1080p
    set "FORMAT=bestvideo[height<=1080][ext=mp4]+bestaudio[ext=m4a]/best[height<=1080][ext=mp4]"
    set "OUTPUT_FOLDER=video"
    goto afterRes

:setMax
    set "FORMAT=bestvideo[ext=mp4]+bestaudio[ext=m4a]/best[ext=mp4]"
    set "OUTPUT_FOLDER=video"
    goto afterRes

:afterRes
echo [INFO] Selected format: "!FORMAT!"
echo [INFO] Save folder: "!OUTPUT_FOLDER!"

:: Request trim times
set /p START_MIN=Enter start minute (e.g. 0): 
set /p END_MIN=Enter end minute (e.g. 2): 
set "START_TIME=00:!START_MIN!:00"
set "END_TIME=00:!END_MIN!:00"

echo [INFO] Trim start time: !START_TIME!
echo [INFO] Trim end time: !END_TIME!

if not exist "!OUTPUT_FOLDER!" mkdir "!OUTPUT_FOLDER!"

:: Set filename template
set "VIDEO_TEMP=!OUTPUT_FOLDER!\%%(title)s.%%(ext)s"

echo.
echo [INFO] Starting download...
yt-dlp.exe !AUDIO_OPTIONS! -f "!FORMAT!" -o "!VIDEO_TEMP!" "!URL_SAFE!" --restrict-filenames --retries 5 --fragment-retries 10 --socket-timeout 60

if !ERRORLEVEL! neq 0 (
    echo [ERROR] Download failed.
    pause
    exit /b
)

:: Find the downloaded file
for %%F in ("!OUTPUT_FOLDER!\*.mp4") do (
    set "FILE_NAME=%%F"
    goto foundFile
)

echo [ERROR] No downloaded file found!
pause
exit /b

:foundFile
echo [INFO] Downloaded file: "!FILE_NAME!"

:: Check if file exists before renaming
if not exist "!FILE_NAME!" (
    echo [ERROR] File not found after download.
    pause
    exit /b
)

:: Clean filename (remove non-ASCII characters)
for /f "tokens=* delims=" %%A in ('powershell -Command "$input = '%FILE_NAME%'; $input -replace '[^\x20-\x7E]', '' -replace '\s+', '_'"') do set "CLEANED_NAME=%%A"

:: Rename file if necessary
if not "!FILE_NAME!"=="!CLEANED_NAME!" (
    ren "!FILE_NAME!" "!CLEANED_NAME!"
    set "FILE_NAME=!CLEANED_NAME!"
)

:: Verify if file exists after renaming
if not exist "!FILE_NAME!" (
    echo [ERROR] File not found after renaming.
    pause
    exit /b
)

echo [INFO] Cleaned file name: "!FILE_NAME!"

:: Define trimmed file output
for %%X in ("!FILE_NAME!") do set "TRIMMED_FILE=trim\%%~nX_trimmed%%~xX"

:: Process trim
echo [INFO] Trimming file...
ffmpeg -i "!FILE_NAME!" -ss !START_TIME! -to !END_TIME! -c copy "!TRIMMED_FILE!"
if errorlevel 1 (
    echo [ERROR] Trim failed.
) else (
    echo [INFO] Trim completed successfully: "!TRIMMED_FILE!"
    del /f "!FILE_NAME!"
    echo [INFO] Original file deleted.
)

echo.
echo [INFO] Process completed. Trimmed files are in "trim" folder.

:: Open folder
start "" "!OUTPUT_FOLDER!"

pause
exit
