import * as fs from 'fs/promises';
import * as path from 'path';
import dotenv from 'dotenv';
import { readJsonToPng } from '../lib/util';
import { generateVideo } from '../lib/video-generator';

dotenv.config();

const inputDir = './input';
const outputDir = './generated/video';

const COMFY_BASE_URL = process.env.SERVER1_COMFY_BASE_URL!;
const COMFY_OUTPUT_DIR = process.env.SERVER1_COMFY_OUTPUT_DIR!;


interface PngMetadata {
    imagePrompt: string;
    videoPrompt: string;
}

async function main() {
    await fs.mkdir(outputDir, { recursive: true });

    const files = await fs.readdir(inputDir);
    const pngFiles = files.filter(file => path.extname(file).toLowerCase() === '.png');

    for (let i = 0; i < pngFiles.length; i++) {
        const file = pngFiles[i];

        const inputFile = path.join(inputDir, file);
        const metadata = await readJsonToPng(inputFile) as PngMetadata;

        if (metadata && metadata.videoPrompt) {
            console.log(`Processing ${file} for video generation.`);

            const originalFileName = path.parse(file).name;
            const nameParts = originalFileName.split('_');
            const promptIndex = nameParts[nameParts.length - 1];
            const newFileName = `product_${i}_${promptIndex}.mp4`;
            const outputPath = path.join(outputDir, newFileName);

            try {
                await fs.access(outputPath);
                console.log(`File ${newFileName} already exists, skipping.`);
                continue;
            } catch (error) {
                // File does not exist, proceed with generation
            }

            console.log(`Generating video for prompt: "${metadata.videoPrompt}"`);

            const inputfolderFullpath = COMFY_OUTPUT_DIR.replace("output", "input");
            await fs.copyFile(inputFile, path.join(inputfolderFullpath, file));

            try {
                await generateVideo(
                    metadata.videoPrompt,
                    file,
                    newFileName,
                    COMFY_BASE_URL,
                    COMFY_OUTPUT_DIR
                );

                console.log(`Successfully generated and saved ${newFileName}`);
            } catch (error) {
                console.error(`Error generating video for ${file}:`, error);
            }
        } else {
            console.log(`Skipping ${file}, no valid videoPrompt metadata found.`);
        }
    }
}

main().catch(console.error);
