import fs from 'fs';
import path from 'path';
import crypto from 'crypto';
import { generateImage } from '../../lib/image-generator-style-faceswap';
import { logger } from '../../lib/logger';
import dotenv from 'dotenv';

dotenv.config();

const scenesFilePath = path.resolve(process.cwd(), 'src/musicspot_generator/v2/scenes.json');
const faceFilePath = path.resolve(process.cwd(), 'src/musicspot_generator/v2/face.png');
const GENERATED_DIR = path.resolve('generated');
const DEFAULT_SIZE = { width: 1280, height: 720 };

interface Scene {
    scene: string;
    imagePrompt: {
        description: string,
        style: string,
        lighting: string,
        outfit: string,
        location: string,
        poses: string,
        angle: string,
    };
    videoPromp: string;
    baseImagePath: string;
}

const COMFY_BASE_URL = process.env.COMFY_BASE_URL;
const COMFY_OUTPUT_DIR = process.env.COMFY_OUTPUT_DIR;

async function generatePhotos() {
    if (!COMFY_BASE_URL || !COMFY_OUTPUT_DIR) {
        throw new Error('COMFY_BASE_URL or COMFY_OUTPUT_DIR is not defined in the .env file');
    }

    const scenesFileContent = fs.readFileSync(scenesFilePath, 'utf-8');
    const scenesData: { scenes: Scene[] } = JSON.parse(scenesFileContent);

    for (const scene of scenesData.scenes) {
        const hash = crypto.createHash('sha256').update(scene.baseImagePath).digest('hex');
        const imgFileName = `${hash}.png`;
        const outputFilePath = path.join(GENERATED_DIR, imgFileName);

        if (fs.existsSync(outputFilePath)) {
            logger.info(`Skipping already generated photo for: ${scene.baseImagePath}`);
            continue;
        }

        logger.info(`Generating photo for: ${scene.baseImagePath}`);

        try {
            await generateImage(
                `Scary realistic photo, ${scene.imagePrompt.location},${scene.imagePrompt.angle},${scene.imagePrompt.lighting},${scene.imagePrompt.outfit}`,
                faceFilePath,
                scene.baseImagePath,
                imgFileName,
                COMFY_BASE_URL,
                COMFY_OUTPUT_DIR,
                DEFAULT_SIZE
            );
            logger.info(`Successfully generated photo: ${imgFileName}`);
        } catch (error) {
            logger.error(`Error generating photo for scene ${scene.scene}:`, error);
        }
    }
}

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