import { PrismaClient } from '@prisma/client';
import { parseBuffer } from 'music-metadata';
import { readFile, writeFile, mkdir, access } from 'fs/promises';
import path from 'path';
import { fileURLToPath } from 'url';

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

// Adjust path to reach root from scripts/
const prisma = new PrismaClient();

async function migrate() {
    // Check if migration already ran
    const flagPath = path.join(process.cwd(), '.covers-migrated');
    try {
        await access(flagPath);
        console.log('✅ Cover migration already completed (flag file exists). Skipping...');
        return;
    } catch {
        // Flag file doesn't exist, proceed with migration
    }

    console.log('Starting cover art migration...');

    try {
        // Find songs without cover image
        const songs = await prisma.song.findMany({
            where: {
                coverImage: null
            }
        });

        console.log(`Found ${songs.length} songs without cover image.`);

        if (songs.length === 0) {
            console.log('✅ All songs already have cover images!');
            await writeFile(flagPath, new Date().toISOString());
            return;
        }

        let processed = 0;
        let successful = 0;

        for (const song of songs) {
            try {
                const filePath = path.join(process.cwd(), 'public/uploads', song.filename);

                const buffer = await readFile(filePath);
                const metadata = await parseBuffer(buffer);
                const picture = metadata.common.picture?.[0];

                if (picture) {
                    const extension = picture.format.split('/')[1] || 'jpg';
                    const coverFilename = `cover-${Date.now()}-${Math.floor(Math.random() * 1000)}.${extension}`;
                    const coverPath = path.join(process.cwd(), 'public/uploads/covers', coverFilename);

                    // Ensure directory exists
                    await mkdir(path.dirname(coverPath), { recursive: true });
                    await writeFile(coverPath, picture.data);

                    // Update DB
                    await prisma.song.update({
                        where: { id: song.id },
                        data: { coverImage: coverFilename }
                    });

                    successful++;
                }
                processed++;
            } catch (e) {
                console.error(`❌ Failed to process ${song.title}:`, e.message);
                processed++;
            }
        }

        console.log(`✅ Cover migration completed: ${successful}/${processed} songs processed successfully.`);

        // Create flag file to prevent re-running
        await writeFile(flagPath, new Date().toISOString());
        console.log(`🏁 Created flag file: ${flagPath}`);
    } catch (e) {
        console.error('Migration failed:', e);
    } finally {
        await prisma.$disconnect();
    }
}

migrate();
