@echo off
title YouTube Video Downloader (prefer H.264)
setlocal EnableDelayedExpansion

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

:: Ask for URL
set /p URL=Enter YouTube URL: 
echo "!URL!" | findstr /C:"youtube.com" >nul 2>&1 || (
    echo [ERROR] Not a YouTube URL.
    pause & exit /b
)
set "URL_SAFE=%URL:&=^&%"

:: Menu
echo.
echo [INFO] Select option:
echo [0] MP3 (Audio)
echo [1] 480p (prefer H.264)
echo [2] 720p (prefer H.264)
echo [3] 1080p (prefer H.264)
echo [4] Maximum (prefer H.264)
set /p RES=Enter option (0-4): 

if "!RES!"=="" echo [ERROR] No option selected.&pause&exit /b
if "!RES!"=="0" goto audio
if "!RES!"=="1" goto p480
if "!RES!"=="2" goto p720
if "!RES!"=="3" goto p1080
if "!RES!"=="4" goto pmax
echo [ERROR] Invalid option.&pause&exit /b

:audio
set "FORMAT=140"
set "OUTPUT=audio"
set "AUDIO=-x --audio-format mp3 --audio-quality 320K"
goto aftersel

:p480
set "FORMAT=bestvideo[height<=480][ext=mp4][vcodec^=avc1]+bestaudio[ext=m4a]/bestvideo[height<=480][ext=mp4]+bestaudio[ext=m4a]/best[height<=480]"
set "OUTPUT=video"
goto aftersel

:p720
set "FORMAT=bestvideo[height<=720][ext=mp4][vcodec^=avc1]+bestaudio[ext=m4a]/bestvideo[height<=720][ext=mp4]+bestaudio[ext=m4a]/best[height<=720]"
set "OUTPUT=video"
goto aftersel

:p1080
set "FORMAT=bestvideo[height<=1080][ext=mp4][vcodec^=avc1]+bestaudio[ext=m4a]/bestvideo[height<=1080][ext=mp4]+bestaudio[ext=m4a]/best[height<=1080]"
set "OUTPUT=video"
goto aftersel

:pmax
set "FORMAT=bestvideo[ext=mp4][vcodec^=avc1]+bestaudio[ext=m4a]/bestvideo[ext=mp4]+bestaudio[ext=m4a]/bestvideo+bestaudio/best"
set "OUTPUT=video"
goto aftersel

:aftersel
:: Playlist detection -> timestamped subfolder
echo "!URL_SAFE!" | findstr /C:"list=" >nul 2>&1
if !ERRORLEVEL! == 0 (
    for /f %%A in ('powershell -Command "Get-Date -Format \"yyyy-MM-dd_HH.mm\""') do set "DATE=%%A"
    set "OUTPUT=!OUTPUT!\!DATE!"
)
if not exist "!OUTPUT!" mkdir "!OUTPUT!"

set "FILE=!OUTPUT!\%%(title).50s.%%(ext)s"

:: Preferential sorting: H.264 first, then res, fps, filesize
set "FORMAT_SORT=--format-sort vcodec:avc1,res,fps,filesize"

echo.
echo [INFO] Detecting stream format...
yt-dlp.exe !FORMAT_SORT! -f "!FORMAT!" --print "FORMAT: %%(format_id)s | v=%%(vcodec)s a=%%(acodec)s | res=%%(resolution)s | fps=%%(fps)s | ext=%%(ext)s" --skip-download "!URL_SAFE!"
if !ERRORLEVEL! neq 0 (
    echo [ERROR] No matching format found.
    pause & exit /b
)

echo.
echo [INFO] Downloading...
yt-dlp.exe !FORMAT_SORT! -f "!FORMAT!" !AUDIO! -o "!FILE!" "!URL_SAFE!" --restrict-filenames --retries 5 --fragment-retries 10 --socket-timeout 60
if !ERRORLEVEL! neq 0 (
    echo [ERROR] Download failed.
    pause & exit /b
)

echo.
echo [OK] Done. Files saved in "!OUTPUT!"
start "" "!OUTPUT!"
pause
exit
