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

dotenv.config();

const inputFolder = './input';
const prompt = "a girl making a cute pose, static camera";
b
async function main() {
    try {
        const files = await fs.readdir(inputFolder);
        const pngFiles = files.filter(file => path.extname(file).toLowerCase() === '.png');

        if (pngFiles.length === 0) {
            console.log('No PNG files found in the input folder.');
            return;
        }

        const comfyBaseUrl = process.env.SERVER2_COMFY_BASE_URL;
        const comfyOutputDir = process.env.SERVER2_COMFY_OUTPUT_DIR;

        if (!comfyBaseUrl || !comfyOutputDir) {
            console.error('Please define SERVER1_COMFY_BASE_URL and SERVER1_COMFY_OUTPUT_DIR in your .env file.');
            return;
        }

        const comfyInputDir = comfyOutputDir.replace('output', 'input');


        for (const file of pngFiles) {
            const inputImagePath = path.join(inputFolder, file);
            const comfyInputImagePath = path.join(comfyInputDir, file);

            console.log(`Processing ${file}...`);

            try {
                await fs.access(inputImagePath);
                // Copy file to comfy input directory
                await fs.copyFile(inputImagePath, comfyInputImagePath);
                console.log(`Copied ${file} to ComfyUI input directory.`);
            } catch (e) {
                console.error(`Error copying file ${file}:`, e);
                continue;
            }


            const newFileName = `${path.parse(file).name}.mp4`;
            try {
                const generatedVideoPath = await generateVideo(
                    prompt,
                    file, // Pass only the filename as per instructions
                    newFileName,
                    comfyBaseUrl,
                    comfyOutputDir
                );
                console.log(`Successfully generated video for ${file} at: ${generatedVideoPath}`);
            } catch (e: any) {
                if (e.code === 'ECONNREFUSED' || e.code === 'ETIMEDOUT') {
                    console.error(`\nError: Connection to ComfyUI server at ${comfyBaseUrl} failed.`);
                    console.error('Please ensure the ComfyUI server is running and accessible.');
                    break;
                } else {
                    console.error(`An error occurred while generating video for ${file}:`, e);
                }
            }
        }
    } catch (error) {
        console.error('An unexpected error occurred:', error);
    }
}

main();
