import { NextResponse } from 'next/server';
import { exec } from 'child_process';
import util from 'util';
import fs from 'fs-extra';
import path from 'path';
import { CheckMQAResponse } from '@/types';

const execPromise = util.promisify(exec);

export async function POST(request: Request) {
    try {
        const { albumPath } = await request.json();

        if (!albumPath || !(await fs.pathExists(albumPath))) {
            return NextResponse.json({ error: 'Invalid album path' }, { status: 400 });
        }

        // Find all FLAC files
        const files = await fs.readdir(albumPath);
        const flacFiles = files.filter(f => f.toLowerCase().endsWith('.flac'));

        if (flacFiles.length === 0) {
            return NextResponse.json({ error: 'No FLAC files found' }, { status: 400 });
        }

        let mqaDetected = false;
        let outputLog = "";

        // Check all files
        for (const file of flacFiles) {
            const filePath = path.join(albumPath, file);
            const command = `salmon check mqa "${filePath}"`;

            try {
                const { stdout } = await execPromise(command);
                const isMQA = !stdout.includes('Did not find MQA syncword');

                outputLog += `[${file}]: ${isMQA ? "MQA DETECTED" : "Clean"}\n`;

                if (isMQA) {
                    mqaDetected = true;
                }
            } catch (e) {
                const errorMessage = e instanceof Error ? e.message : String(e);
                outputLog += `[${file}]: Error - ${errorMessage}\n`;
            }
        }

        const response: CheckMQAResponse = {
            success: true,
            isMQA: mqaDetected,
            output: outputLog
        };

        return NextResponse.json(response);

    } catch (error) {
        console.error('Error checking MQA:', error);
        return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
    }
}
