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

dotenv.config();

const inputFolderPath = path.join(__dirname, '..', '..', '..', 'input/static');
const generatedFolderPath = path.join(__dirname, '..', '..', '..', 'generated');

async function processImages() {
    try {
        const imageFiles = fs.readdirSync(inputFolderPath);

        for (const imageFile of imageFiles) {
            const imagePath = path.join(inputFolderPath, imageFile);

            try {
                const hash = crypto.createHash('sha256').update(imageFile).digest('hex');
                const outputVideoFileName = `${hash}.mp4`;
                const outputVideoPath = path.join(generatedFolderPath, outputVideoFileName);

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

                console.log(`Generating video prompt for image ${imageFile}...`);
                const promptResult = await callLMStudioAPIWithFile(
                    imagePath,
                    `
                    Generate a short, dancing video prompt for an image located at ${imagePath}. 
                    Return the result in this format: {"result":""}
                    Instruction:
                    - Find best dancing expression based on the photo
                `);
                const videoPrompt = promptResult.result;
                console.log(`Video prompt ${videoPrompt}`);

                if (!videoPrompt) {
                    console.error(`Could not generate video prompt for image ${imageFile}`);
                    continue;
                }

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

                await generateVideo(
                    videoPrompt,
                    imagePath,
                    outputVideoPath,
                    process.env.COMFY_BASE_URL!,
                    process.env.COMFY_OUTPUT_DIR!,
                    { width: 1280, height: 720 }
                );
                console.log(`Video for image ${imageFile} saved to ${outputVideoPath}`);
            } catch (e) {
                console.error(`Error processing image ${imageFile}:`, e);
                continue;
            }
        }
    } catch (error) {
        console.error('Error processing images:', error);
    }
}

processImages();
