import { NextRequest, NextResponse } from 'next/server'

const TTS_SERVICE_URL = process.env.TTS_SERVICE_URL || 'http://compliance-tts-service:8095'
const LITELLM_URL = process.env.LITELLM_URL || 'https://llm-dev.meghsakha.com'
const LITELLM_API_KEY = process.env.LITELLM_API_KEY || ''

// English via OVH is opt-in (set OVH_TTS_URL_EN). German always uses the
// compliance TTS service (Edge TTS de-DE-ConradNeural → Piper fallback).
const OVH_EN = process.env.OVH_TTS_URL_EN
  ? {
      url: process.env.OVH_TTS_URL_EN,
      voice: process.env.OVH_TTS_VOICE_EN || 'English-US.Female-1',
      languageCode: 'en-US',
    }
  : null

const SAMPLE_RATE_HZ = parseInt(process.env.OVH_TTS_SAMPLE_RATE || '16000', 10)

export async function POST(request: NextRequest) {
  try {
    const body = await request.json()
    const { text, language = 'de' } = body

    if (!text || typeof text !== 'string') {
      return NextResponse.json({ error: 'Text is required' }, { status: 400 })
    }

    if (language === 'en' && OVH_EN) {
      return await synthesizeViaOvh(text, OVH_EN)
    }

    // Fix pronunciation of English words in German TTS
    let ttsText = text
    if (language === 'de') {
      ttsText = ttsText
        .replace(/BreakPilot/g, 'Brejk Peilott')
        .replace(/Breakpilot/g, 'Brejk Peilott')
        .replace(/COMPLAI/g, 'Complei')
        .replace(/Executive Summary/g, 'Exekjutiv Sammäri')
        .replace(/Onepager/g, 'Wann-Päidscher')
        .replace(/Land & Expand/g, 'Länd änd Expänd')
        .replace(/Compliance Optimizer/g, 'Compliance Optimeiser')
        .replace(/Deep Dive/g, 'Diep Deiv')
        .replace(/Use Case/g, 'Juhs Käis')
        .replace(/Re-Ranking/g, 'Rie-Ränking')
        .replace(/Reranking/g, 'Rie-Ränking')
        .replace(/Cross-Encoder/g, 'Kross-Enkoder')
        .replace(/Embeddings/g, 'Embäddings')
        .replace(/Channel/g, 'Tschännel')
        .replace(/Break-Even/g, 'Bräik-Ihwen')
        .replace(/Pipeline/g, 'Peiplein')
        .replace(/Upside/g, 'Appseid')
        .replace(/Cloud/g, 'Klaud')
        .replace(/Marketplace/g, 'Marketpläis')
        .replace(/Enterprise/g, 'Enterpreis')
        .replace(/Startup/g, 'Startapp')
        .replace(/Deploy/g, 'Diploi')
        .replace(/Scaling/g, 'Skähling')
        .replace(/Stack/g, 'Stäck')
        .replace(/Tech-Stack/g, 'Teck-Stäck')
    }

    return await synthesizeViaComplianceService(ttsText, language)
  } catch (error) {
    console.error('TTS proxy error:', error)
    return NextResponse.json({ error: 'TTS service not reachable' }, { status: 503 })
  }
}

async function synthesizeViaOvh(
  text: string,
  cfg: { url: string; voice: string; languageCode: string },
): Promise<NextResponse> {
  const res = await fetch(cfg.url, {
    method: 'POST',
    headers: {
      accept: 'application/octet-stream',
      'Content-Type': 'application/json',
      Authorization: `Bearer ${LITELLM_API_KEY}`,
    },
    body: JSON.stringify({
      encoding: 1, // LINEAR_PCM
      language_code: cfg.languageCode,
      sample_rate_hz: SAMPLE_RATE_HZ,
      text,
      voice_name: cfg.voice,
    }),
    signal: AbortSignal.timeout(30000),
  })

  if (!res.ok) {
    const errorText = await res.text().catch(() => '')
    console.error('OVH TTS error:', res.status, errorText.slice(0, 500))
    return NextResponse.json({ error: `OVH TTS error (${res.status})` }, { status: 502 })
  }

  const pcm = Buffer.from(await res.arrayBuffer())
  const wav = pcm.subarray(0, 4).toString('ascii') === 'RIFF' ? pcm : wrapPcmAsWav(pcm, SAMPLE_RATE_HZ)

  return new NextResponse(new Uint8Array(wav), {
    headers: {
      'Content-Type': 'audio/wav',
      'Cache-Control': 'no-cache',
      'X-TTS-Source': 'ovh',
    },
  })
}

async function synthesizeViaComplianceService(text: string, language: string): Promise<NextResponse> {
  const res = await fetch(`${TTS_SERVICE_URL}/synthesize-direct`, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ text, language }),
    signal: AbortSignal.timeout(30000),
  })

  if (!res.ok) {
    const errorText = await res.text().catch(() => '')
    console.error('TTS service error:', res.status, errorText.slice(0, 500))
    return NextResponse.json({ error: `TTS service error (${res.status})` }, { status: 502 })
  }

  const audioBuffer = await res.arrayBuffer()
  return new NextResponse(audioBuffer, {
    headers: {
      'Content-Type': 'audio/mpeg',
      'Cache-Control': 'no-cache',
      'X-TTS-Cache': res.headers.get('X-TTS-Cache') || 'unknown',
      'X-TTS-Source': 'compliance',
    },
  })
}

// Prepend a minimal 44-byte WAV header to raw 16-bit mono PCM.
// Used only for OVH EN if enabled — OVH Riva returns bare PCM samples.
function wrapPcmAsWav(pcm: Buffer, sampleRateHz: number): Buffer {
  const numChannels = 1
  const bitsPerSample = 16
  const byteRate = (sampleRateHz * numChannels * bitsPerSample) / 8
  const blockAlign = (numChannels * bitsPerSample) / 8
  const dataSize = pcm.length

  const header = Buffer.alloc(44)
  header.write('RIFF', 0)
  header.writeUInt32LE(36 + dataSize, 4)
  header.write('WAVE', 8)
  header.write('fmt ', 12)
  header.writeUInt32LE(16, 16)
  header.writeUInt16LE(1, 20)
  header.writeUInt16LE(numChannels, 22)
  header.writeUInt32LE(sampleRateHz, 24)
  header.writeUInt32LE(byteRate, 28)
  header.writeUInt16LE(blockAlign, 32)
  header.writeUInt16LE(bitsPerSample, 34)
  header.write('data', 36)
  header.writeUInt32LE(dataSize, 40)

  return Buffer.concat([header, pcm])
}
