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

dotenv.config();

interface Scene {
    scene: string;
    videoPrompt: string;
    baseImagePath: string;
}

const scenesFilePath = path.join(__dirname, 'scenes.json');
const generatedFolderPath = path.join(__dirname, '..', '..', '..', 'generated');

async function processScenes() {
    try {
        const scenesData = fs.readFileSync(scenesFilePath, 'utf-8');
        const scenes: Scene[] = JSON.parse(scenesData).scenes;

        for (const scene of scenes) {

            try {
                const hash = crypto.createHash('sha256').update(scene.baseImagePath).digest('hex');
                const imageFileName = `${hash}.png`;
                const imagePath = path.join(generatedFolderPath, imageFileName);

                if (fs.existsSync(imagePath)) {
                    const outputVideoFileName = `${hash}.mp4`;
                    const outputVideoPath = path.join(generatedFolderPath, outputVideoFileName);

                    if (fs.existsSync(outputVideoPath)) {
                        console.log(`Video already exists for scene ${scene.scene}, skipping.`);
                        continue;
                    }

                    console.log(`Generating video for scene ${scene.scene}...`);

                    await generateVideo(
                        scene.videoPrompt,
                        imagePath,
                        outputVideoPath,
                        process.env.COMFY_BASE_URL!,
                        process.env.COMFY_OUTPUT_DIR!,
                        { width: 1280, height: 720 }
                    );
                    console.log(`Video for scene ${scene.scene} saved to ${outputVideoPath}`);
                } else {
                    console.warn(`Image not found for scene ${scene.scene}: ${imagePath}`);
                }
            } catch (e) {
                continue;
            }

        }
    } catch (error) {
        console.error('Error processing scenes:', error);
    }
}

processScenes();
