import axios from 'axios';
import { getPiperUrl } from '../config.js';

export interface PiperSynthesisParams {
  text: string;
  lang?: string;
}

class PiperHttpService {
  async synthesize(params: PiperSynthesisParams): Promise<Buffer> {
    const piperUrl = getPiperUrl();
    if (!piperUrl) throw new Error('PIPER_URL not configured');

    const speakerId = params.lang === 'en' ? 1 : 0;

    const response = await axios.post(
      `${piperUrl}/api/tts`,
      { text: params.text, speaker_id: speakerId },
      { responseType: 'arraybuffer', timeout: 30_000 },
    );

    return Buffer.from(response.data, 'binary');
  }
}

export const piperService = new PiperHttpService();
