/**
 * Utility to convert SRT (SubRip) subtitle format to WebVTT format
 */
export class SrtConverter {
    /**
     * Converts SRT content to WebVTT content
     * @param srtContent The content of an SRT file as a string
     * @returns The converted WebVTT content
     */
    public static convertToVtt(srtContent: string): string {
        // 1. Ensure the WEBVTT header is present
        let vtt = 'WEBVTT\n\n';

        // 2. Strip UTF-8 BOM if present, normalise line endings, split into blocks
        const blocks = srtContent
            .replace(/^\uFEFF/, '')   // BOM — trim() does not remove it
            .replace(/\r\n/g, '\n')
            .replace(/\r/g, '\n')
            .trim()
            .split(/\n\n+/);

        for (const block of blocks) {
            const lines = block.split('\n');
            if (lines.length < 2) continue;

            // The first line is usually the index (can be skipped for VTT)
            // The second line is the timestamp
            let timestampLineIndex = 0;
            if (/^\d+$/.test(lines[0])) {
                timestampLineIndex = 1;
            }

            if (lines[timestampLineIndex] && lines[timestampLineIndex].includes(' --> ')) {
                // 3. Convert time format: 00:00:01,000 -> 00:00:01.000
                const vttTimestamp = lines[timestampLineIndex].replace(/,/g, '.');
                vtt += vttTimestamp + '\n';

                // 4. Add the rest of the text lines
                for (let i = timestampLineIndex + 1; i < lines.length; i++) {
                    vtt += lines[i] + '\n';
                }
                vtt += '\n';
            }
        }

        return vtt;
    }
}
