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

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

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

:: Validate the URL
echo "!URL!" | findstr /C:"tiktok.com" >nul 2>&1
if !ERRORLEVEL! equ 0 (
    :: Check if the URL is a photo post
    echo "!URL!" | findstr /C:"/photo/" >nul 2>&1
    if !ERRORLEVEL! equ 0 (
        echo [ERROR] The provided URL points to a photo post, which is not supported.
        pause
        exit /b
    )

    :: Check if the URL is a video post
    echo "!URL!" | findstr /C:"/video/" >nul 2>&1
    if !ERRORLEVEL! neq 0 (
        echo [WARNING] The URL does not explicitly indicate a video. Attempting to verify...

        :: Attempt to extract metadata to determine if it's a video
        yt-dlp.exe --dump-json --skip-download "!URL!" > metadata.json 2>nul
        if exist metadata.json (
            findstr /C:"\"is_live\": true" metadata.json >nul 2>&1
            if !ERRORLEVEL! equ 0 (
                echo [ERROR] The provided URL points to a live stream, which is not supported.
                del metadata.json
                pause
                exit /b
            )

            findstr /C:"\"ext\": \"mp4\"" metadata.json >nul 2>&1
            if !ERRORLEVEL! neq 0 (
                echo [ERROR] The provided URL does not point to a downloadable video.
                del metadata.json
                pause
                exit /b
            )
            del metadata.json
        ) else (
            echo [ERROR] Unable to retrieve metadata. The URL may not point to a valid video.
            pause
            exit /b
        )
    )
) else (
    echo [ERROR] The entered URL does not appear to be from TikTok.
    pause
    exit /b
)

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

echo [INFO] Processing TikTok URL...

:: Set download folder and filename template
:: Limits title to 50 characters to prevent overly long filenames
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 3 (
        timeout /t 1 >nul
        goto download_loop
    ) else (
        echo [ERROR] Unable to download the video after 3 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=tiktok_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
