import Elysia, { t } from "elysia";
import { ElysiaWS } from "elysia/ws";
import { tts_tiktok, ensureOutputDir } from "../lib/tts_tiktok";
import fs from "fs";
import path from "path";
import _ from "lodash";

const { OUTPUT_DIR_FINAL } = await ensureOutputDir();
const wsClients = new Set<ElysiaWS>();

const TTSTiktok = new Elysia({
    prefix: '/tts-tiktok',
    detail: { description: 'TTS TikTok API', summary: 'TTS TikTok API', tags: ['tts-tiktok'] },
}).post('/generate', async ({ body }) => {
    const { file_name, text, sessionId } = body
    const nameFile = _.snakeCase(file_name)
    const audio = await tts_tiktok({ text, sessionId, fileName: nameFile })
    return {
        success: true,
        data: audio
    }
}, {
    body: t.Object({
        file_name: t.String(),
        text: t.String(),
        sessionId: t.String()
    }),
    detail: {
        description: 'Generate TTS TikTok',
        summary: 'Generate TTS TikTok'
    }
})
    .get("/list-audio", () => {
        const files = fs.readdirSync(OUTPUT_DIR_FINAL)
        return {
            data: files
        }
    }, {
        detail: {
            description: 'List all audio files',
            summary: 'List all audio files'
        }
    })
    .get("/download/:filename", ({ params }) => {
        console.log(params.filename)
        const filePath = path.join(OUTPUT_DIR_FINAL, params.filename);

        if (!fs.existsSync(filePath)) {
            return new Response("Not found", { status: 404 });
        }

        const file = Bun.file(filePath);
        return new Response(file, {
            headers: {
                "Content-Type": "audio/mpeg",
                "Cache-Control": "no-cache",
            },
        });
    })
    .delete("/remove/:filename", ({ params }) => {
        const { filename } = params
        fs.unlinkSync(path.join(OUTPUT_DIR_FINAL, filename))
        return {
            success: true,
            data: filename
        }
    }, {
        params: t.Object({
            filename: t.String()
        }),
        detail: {
            description: 'Delete audio file',
            summary: 'Delete audio file'
        }
    })
    .delete("/clear", () => {
        fs.promises.rmdir(OUTPUT_DIR_FINAL, { recursive: true }).catch(() => { })
        return {
            success: true,
            data: "OK"
        }
    }, {
        detail: {
            description: 'Delete all audio files',
            summary: 'Delete all audio files'
        }
    })
    .ws("/ws", {
        open: (ws) => {
            console.log("Client connected");
            wsClients.add(ws);

        },
        close: (ws) => {
            console.log("Client disconnected");
            wsClients.delete(ws);
        },
        message: (ws, msg) => {
            ws.send("Echo: " + msg);
        }
    })

export default TTSTiktok
