import fs from "fs";
import { constants as fsConstants } from "node:fs";
import { execFile } from "node:child_process";
import { promisify } from "node:util";
import { LIST_FILE_NAME, OUTPUT, TEMP_DIR } from "./chatterbox.env";
import path from "node:path";

const exec = promisify(execFile);

/**
 * Menggabungkan daftar file WAV menggunakan ffmpeg concat demuxer.
 * @param relativeFileNames Array NAMA file WAV yang berada di TEMP_DIR (misal: ['a.wav', 'b.wav']).
 * @param output Path lengkap untuk menyimpan file WAV hasil gabungan.
 */
async function merge(relativeFileNames: string[], output: string): Promise<void> {
    if (relativeFileNames.length === 0) {
        console.warn("⚠️ Tidak ada file untuk digabungkan. Melewati proses.");
        return;
    }

    console.log(`\n🔧 Menggabungkan ${relativeFileNames.length} file WAV menggunakan ffmpeg...`);

    const listFilePath = `${TEMP_DIR}/${LIST_FILE_NAME}`;

    // Perbaikan: Tulis nama file saja tanpa prefix TEMP_DIR agar path valid saat concat
    const listContent = relativeFileNames
        .map((f) => `file '${f.replace(/'/g, "'\\''")}'`)
        .join("\n");

    try {
        await fs.promises.writeFile(listFilePath, listContent, "utf-8");
    } catch (err) {
        console.error(`❌ Gagal menulis file list ${listFilePath}:`, err);
        throw new Error(`Gagal menyiapkan file list untuk ffmpeg.`);
    }

    try {
        await exec("ffmpeg", [
            "-f", "concat",
            "-safe", "0",
            "-i", listFilePath,
            "-c", "copy", // Menggabungkan tanpa re-encoding
            output,
        ]);

        console.log(`✅ File berhasil digabungkan dan disimpan di: ${output}\n`);
    } catch (err) {
        console.error("❌ Kesalahan saat menjalankan ffmpeg:", err);
        if (err instanceof Error && 'stdout' in err) {
            console.error('ffmpeg stderr output:', (err as any).stderr);
        }
        throw new Error(`Penggabungan ffmpeg gagal.`);
    } finally {
        try {
            await fs.promises.unlink(listFilePath);
        } catch {
            console.warn(`⚠️ Gagal menghapus file list ${listFilePath}.`);
        }
    }
}

// --- Fungsi Utama ---
export async function merge_wav(jobs_name: string) {

    const output = path.resolve(OUTPUT, `${jobs_name}.wav`);

    try {
        await fs.promises.access(output, fsConstants.F_OK);
        await fs.promises.unlink(output);
    } catch (error) {}
        

    // Baca daftar file WAV dalam TEMP_DIR
    const allFiles = await fs.promises.readdir(TEMP_DIR);

    const wavFileNames = allFiles
        .filter((f) => f.endsWith(".wav"))
        .sort((a, b) => {
            const aNum = parseInt(a?.split("_")[2] || "0");
            const bNum = parseInt(b?.split("_")[2] || "0");
            return aNum - bNum;
        });

    try {
        await merge(wavFileNames, output);
    } catch (err) {
        console.error("⛔ Proses penggabungan utama gagal.");
        process.exit(1);
    }
}
