import { Router } from 'express';
import { randomUUID } from 'crypto';
import { join } from 'path';
import { mkdirSync, writeFileSync } from 'fs';
import { piperService } from '../services/piper.service.js';
import { getToken } from '../config.js';

const router = Router();

const TTS_AUDIO_DIR = join('/tmp', 'quibot-audio', 'tts');
try { mkdirSync(TTS_AUDIO_DIR, { recursive: true }); } catch { /* ignore */ }

router.post('/', async (req, res) => {
  try {
    const text = (req.query.text as string) || (req.body?.text as string);
    // Accept 'lang' or 'language' — APK sends 'language', old tests use 'lang'
    const lang = (req.query.lang as string) || (req.query.language as string) || 'ca';
    const token = (req.query.token as string) || '';

    if (!text?.trim()) {
      return res.status(400).json({ error: 'Missing query parameter: text' });
    }

    const expectedToken = getToken();
    if (token && token !== expectedToken) {
      return res.status(401).json({ error: 'Unauthorized: invalid token' });
    }

    console.log(`[tts] Generating audio for text (${lang}): "${text.substring(0, 60)}..."`);

    // Ensure Piper subprocess is initialized before synthesis
    await piperService.initWav();

    const wavBuffer = await piperService.synthWav(text.trim());

    const filename = `${randomUUID()}.wav`;
    writeFileSync(join(TTS_AUDIO_DIR, filename), wavBuffer);

    console.log(`[tts] Audio saved: ${filename}`);

    return res.json({
      audioUrl: `/tts-audio/${filename}`,
      filename,
    });
  } catch (err: unknown) {
    const message = err instanceof Error ? err.message : 'Unknown error';
    console.error(`[tts] Error: ${message}`);
    return res.status(500).json({ error: `TTS synthesis failed: ${message}` });
  }
});

export default router;
