@echo off
chcp 65001 >nul
title Platform X Video Downloader
setlocal EnableDelayedExpansion

:: Create "video" folder if it doesn't exist
if not exist "video" mkdir "video"

:: Request Platform X URL from the user
set /p URL=Enter Platform X URL: 

:: Check if the URL contains "twitter.com" or "x.com"
echo "!URL!" | findstr /C:"twitter.com" >nul 2>&1 || echo "!URL!" | findstr /C:"x.com" >nul 2>&1 || (
    echo [ERROR] The entered URL does not appear to be from Platform X.
    pause
    exit /b
)

:: Replace & with ^& for CMD safety
set "URL_SAFE=%URL:&=^&%"

echo [INFO] Processing URL...

:: Set download folder and filename template (limited to 50 characters)
set "OUTPUT_FOLDER=video"
set "VIDEO_TEMP=!OUTPUT_FOLDER!\%%(title).50s.%%(ext)s"

:: Initialize retry counter
set /a attempt=1

:download_loop
echo.
echo [INFO] Attempt %attempt% to download...
echo [INFO] Executing command:
echo yt-dlp.exe -o "!VIDEO_TEMP!" "!URL_SAFE!" --restrict-filenames --retries 5 --fragment-retries 10 --socket-timeout 60
echo.

:: Execute download command
yt-dlp.exe -o "!VIDEO_TEMP!" "!URL_SAFE!" --restrict-filenames --retries 5 --fragment-retries 10 --socket-timeout 60

if ERRORLEVEL 1 (
    echo [ERROR] Download failed on attempt %attempt%.
    set /a attempt+=1
    if %attempt% leq 20 (
        timeout /t 1 >nul
        goto download_loop
    ) else (
        echo [ERROR] Unable to download the video after 20 attempts.
        pause
        exit /b
    )
) else (
    echo [INFO] DOWNLOAD COMPLETED SUCCESSFULLY.
)

:: Select the most recent file from the "video" folder
for /f "delims=" %%F in ('dir /b /a-d /o-d "video\*.mp4"') do (
    set "FILE_NAME=video\%%F"
    goto FoundFile
)
:FoundFile

if not defined FILE_NAME (
    echo [ERROR] No downloaded file found.
    pause
    exit /b
) else (
    echo [INFO] Downloaded file: "!FILE_NAME!"
)

:: Extract filename and extension separately
for %%X in ("!FILE_NAME!") do (
    set "FILE_BASENAME=%%~nX"
    set "FILE_EXT=%%~xX"
)

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

:: Ensure the cleaned filename is not too long (max 50 characters)
set "CLEANED_NAME=!CLEANED_NAME:~0,50!"

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

:: If the cleaned name is empty, use a default name
if "!CLEANED_NAME!"=="" set "CLEANED_NAME=video"

:: Build final sanitized filename (with extension)
set "SANITIZED_FILE=video\!CLEANED_NAME!!FILE_EXT!"

:: Check if the sanitized filename already exists to avoid overwriting
if exist "!SANITIZED_FILE!" (
    set "SANITIZED_FILE=video\!CLEANED_NAME!_%RANDOM%!FILE_EXT!"
)

:: Rename the downloaded file safely
rename "!FILE_NAME!" "!CLEANED_NAME!!FILE_EXT!"
if errorlevel 1 (
    echo [ERROR] Error renaming the file.
) else (
    echo [INFO] File renamed successfully: "!SANITIZED_FILE!"
)

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

pause
exit
