@echo off
title Facebook Video Downloader
setlocal EnableDelayedExpansion

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

:: Request Facebook URL from the user
set /p URL=Enter Facebook URL: 

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

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

echo [INFO] Processing Facebook URL...

:: Set download option to the best quality
set "FORMAT=best"
set "OUTPUT_FOLDER=video"
set "VIDEO_TEMP=!OUTPUT_FOLDER!\%%(title)s.%%(ext)s"

:: Display the executed command (DEBUG)
echo.
echo [INFO] Executing command:
echo yt-dlp.exe -f "!FORMAT!" -o "!VIDEO_TEMP!" "!URL_SAFE!" --restrict-filenames --retries 5 --fragment-retries 10 --socket-timeout 60
echo.

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

if ERRORLEVEL 1 (
    echo.
    echo [ERROR] Failed to download the video.
    pause
    exit /b
)

:: Find the latest downloaded file in 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!"
)

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

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

:: Verify if the 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!"

echo.
echo [INFO] DOWNLOAD COMPLETED SUCCESSFULLY. The file is located in the "!OUTPUT_FOLDER!" folder.

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

pause
exit
