import ffmpeg, { FfprobeStream } from 'fluent-ffmpeg';
import fs from 'fs';
import type { LogWrapper } from './log';

export const defaultVideoThumbB64 =
    '[encoded data, 5192 characters]';

export async function getVideoInfo(filePath: string, logger: LogWrapper) {
    const size = fs.statSync(filePath).size;
    return new Promise<{
        width: number,
        height: number,
        time: number,
        format: string,
        size: number,
        filePath: string
    }>((resolve, reject) => {
        const ffmpegPath = process.env.FFMPEG_PATH;
        if (ffmpegPath)
            ffmpeg.setFfmpegPath(ffmpegPath);
        ffmpeg(filePath).ffprobe((err: any, metadata: ffmpeg.FfprobeData) => {
            if (err) {
                reject(new Error('无法获取视频信息。'));
            } else {
                const videoStream = metadata.streams.find((s: FfprobeStream) => s.codec_type === 'video');
                if (videoStream) {
                    logger.log(`视频尺寸: ${videoStream.width}x${videoStream.height}`);
                } else {
                    return reject(new Error('未找到视频流信息。'));
                }
                resolve({
                    width: videoStream.width!, height: videoStream.height!,
                    time: +(videoStream.duration ?? 10),
                    format: metadata.format.format_name!,
                    size,
                    filePath,
                });
            }
        });
    });
}

export function checkFfmpeg(logger: LogWrapper, newPath: string | null = null): Promise<boolean> {
    return new Promise((resolve) => {
        logger.log('开始检查ffmpeg', newPath);
        if (newPath) {
            ffmpeg.setFfmpegPath(newPath);
        }
        try {
            ffmpeg.getAvailableFormats((err: any) => {
                if (err) {
                    logger.log('ffmpeg is not installed or not found in PATH:', err);
                    resolve(false);
                } else {
                    logger.log('ffmpeg is installed.');
                    resolve(true);
                }
            });
        } catch (e) {
            resolve(false);
        }
    });
}
