@echo off
chcp 65001 >nul
title Facebook Downloader with Trim
setlocal EnableDelayedExpansion

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

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

:: Check if the URL contains "facebook.com"
echo "!URL!" | findstr /C:"facebook.com" >nul 2>&1 || (
    echo [ERROR] Invalid Facebook URL.
    pause
    exit /b
)

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

echo [INFO] Processing Facebook URL...

:: Set download format (best quality)
set "FORMAT=best"
set "OUTPUT_FOLDER=video"
set "VIDEO_TEMP=!OUTPUT_FOLDER!\%%(title)s.mp4"

:: 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!"

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

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] Download failed.
    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 name: !FILE_NAME!
)

:: Clean the filename using PowerShell
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] DOWNLOAD COMPLETED SUCCESSFULLY. Files are in the "trim" folder.

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

pause
exit
