@echo off
REM Check if FFmpeg is in PATH
where ffmpeg >nul 2>&1
if errorlevel 1 (
    echo FFmpeg is not installed or not in PATH.
    pause
    exit /b
)

REM Check if a file was dragged onto the script
if "%~1"=="" (
    echo No file was dragged onto the script.
    pause
    exit /b
)

REM Get the filename without extension
set "filename=%~n1"
set "outputfile=%filename%_chapters.csv"

REM Extract chapters using FFmpeg
ffmpeg -i "%~1" -f ffmetadata chapters.txt

REM Check if chapters.txt was created
if not exist chapters.txt (
    echo No chapters found in the file.
    pause
    exit /b
)

REM Convert chapters.txt to CSV using tab as a separator
(
echo Marker Name	Description	In	Out	Duration	Marker Type
setlocal enabledelayedexpansion
set "last_start_time="
for /f "tokens=1,2 delims==" %%A in ('findstr /c:"START=" /c:"title=" chapters.txt') do (
    if "%%A"=="START" (
        set "timestamp=%%B"
        REM Convert timestamp from milliseconds to seconds assuming 60fps
        set /a "milliseconds=timestamp %% 1000"
        set /a "total_seconds=timestamp / 1000"
        set /a "frames=(milliseconds * 60) / 1000"
        set /a "seconds=total_seconds %% 60"
        set /a "minutes=(total_seconds / 60) %% 60"
        set /a "hours=total_seconds / 3600"

        REM Pad values to ensure proper format
        if !hours! lss 10 set "hours=0!hours!"
        if !minutes! lss 10 set "minutes=0!minutes!"
        if !seconds! lss 10 set "seconds=0!seconds!"
        if !frames! lss 10 set "frames=0!frames!"

        set "formatted_time=!hours!:!minutes!:!seconds!:!frames!"
        
        if defined last_start_time (
            echo !title!		!last_start_time!	!last_start_time!	00:00:00:00	Chapter
        )
        set "last_start_time=!formatted_time!"
    ) else if "%%A"=="title" (
        set "title=%%B"
    )
)
REM Handle the last chapter
if defined last_start_time (
    echo !title!		!last_start_time!	!last_start_time!	00:00:00:00	Chapter
)
) > "%outputfile%"

REM Clean up temporary files
del chapters.txt

echo Chapter markers saved to %outputfile%

start "" python 0csv_to_xml.py
pause