import fs from 'fs';
import path from 'path';
import { callLMStudioAPIWithFile } from '../../lib/lmstudio';
import { logger } from '../../lib/logger';

const promptInstructions = `
    Video prompt: No slowmotion, Be creative and generate gengle action scene.
    `;
6
const inputDir = path.resolve(process.cwd(), 'input/static');
const outputFilePath = path.resolve(process.cwd(), 'src/musicspot_generator/v2/scenes.json');

interface Scene {
    scene: string;
    imagePrompt: string;
    videoPromp: string;
    baseImagePath: string;
}

async function processImages() {
    const imageFiles = fs.readdirSync(inputDir).filter(file => /\.(png|jpg|jpeg)$/i.test(file));
    let scenes: { scenes: Scene[] } = { scenes: [] };

    if (fs.existsSync(outputFilePath)) {
        const fileContent = fs.readFileSync(outputFilePath, 'utf-8');
        if (fileContent) {
            scenes = JSON.parse(fileContent);
        }
    }

    for (const imageFile of imageFiles) {
        const imagePath = path.resolve(inputDir, imageFile);
        const absoluteImagePath = path.resolve(imagePath);

        const existingScene = scenes.scenes.find(s => s.baseImagePath === absoluteImagePath);
        if (existingScene) {
            logger.info(`Skipping already processed image: ${imageFile}`);
            continue;
        }

        logger.info(`Processing image: ${imageFile} `);

        const prompt = `
            Analyze the provided image and generate a JSON object with the following structure:
{
    "scenes": [
        {
            "scene": "A descriptive title for the scene in the image.",
            "imagePrompt": {
                "description": "A detailed description of the image content.",
                "style": "Art style or photography style of the image.",
                "lighting": "Description of the lighting in the image.",
                "outfit": "Description of the outfit or clothing style in the image.",
                "location": "Description of the location or setting of the image.",
                "poses": "Description of the poses or actions of any subjects in the image.",
                "angle": "Description of the camera angle or perspective of the image.",
            }
            "videoPromp": "Based on the image, create a prompt for a video that shows what might happen next or brings the scene to life.",
            "baseImagePath": "The absolute path of the base image."
        }
    ]
}

Instructions: ${promptInstructions}
`;

        try {
            const result = await callLMStudioAPIWithFile(imagePath, prompt);
            if (result && result.scenes) {
                const newScene = result.scenes[0];
                newScene.baseImagePath = absoluteImagePath; // Ensure the path is correct
                scenes.scenes.push(newScene);

                fs.writeFileSync(outputFilePath, JSON.stringify(scenes, null, 2));
                logger.info(`Successfully processed and saved scene for: ${imageFile} `);
            } else {
                logger.error('Failed to get valid scene data from API for image:', imageFile);
            }
        } catch (error) {
            logger.error(`Error processing image ${imageFile}: `, error);
        }
    }
}

processImages().catch(error => {
    logger.error('An unexpected error occurred:', error);
});
