<?php
// api/tts_diag.php
declare(strict_types=1);

require_once __DIR__ . '/config.php';
header('Content-Type: application/json; charset=utf-8');
header('Access-Control-Allow-Origin: *');

function out($code, $arr){ http_response_code($code); echo json_encode($arr, JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES); exit; }

$provider = strtolower($_GET['p'] ?? 'elevenlabs'); // elevenlabs | openai
$text     = $_GET['t'] ?? 'This is a test from tts_diag.';
$voice    = $_GET['v'] ?? ''; // eleven: voice_id ; openai: alloy/verse/aria...

$saveDir = dirname(__DIR__) . '/public/tts/diag';
@mkdir($saveDir, 0775, true);
$file = $saveDir . '/diag-' . $provider . '-' . time() . '.mp3';

$dbg = [
  'provider' => $provider,
  'env' => [
    'ELEVEN.keySet' => defined('ELEVEN_API_KEY') && ELEVEN_API_KEY !== '',
    'OPENAI.keySet' => defined('OPENAI_API_KEY') && OPENAI_API_KEY !== '',
  ]
];

// simple POST JSON util
$http = function(string $url, array $headers, array $json){
  $h=[]; foreach($headers as $k=>$v){ $h[] = $k.': '.$v; }
  $ch = curl_init($url);
  curl_setopt_array($ch, [
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_POST => true,
    CURLOPT_HTTPHEADER => $h,
    CURLOPT_POSTFIELDS => json_encode($json, JSON_UNESCAPED_UNICODE),
    CURLOPT_HEADER => false,
  ]);
  $body = curl_exec($ch);
  $err  = curl_error($ch);
  $code = (int)curl_getinfo($ch, CURLINFO_HTTP_CODE);
  curl_close($ch);
  return [$code,$err,$body];
};

if ($provider === 'elevenlabs') {
  if (!defined('ELEVEN_API_KEY') || ELEVEN_API_KEY === '') out(400, ['ok'=>false,'error'=>'ELEVENLABS_API_KEY absente (ENV).','dbg'=>$dbg]);
  $voiceId = $voice ?: '21m00Tcm4TlvDq8ikWAM'; // voix publique “Rachel”
  [$code,$err,$body] = $http('https://api.elevenlabs.io/v1/text-to-speech/'.$voiceId, [
    'accept' => 'audio/mpeg',
    'xi-api-key' => ELEVEN_API_KEY,
    'Content-Type' => 'application/json'
  ], [
    'text' => $text,
    'model_id' => 'eleven_multilingual_v2',
    'voice_settings' => ['stability'=>0.5,'similarity_boost'=>0.75],
    'output_format' => 'mp3_44100_128'
  ]);
  $dbg['http'] = ['code'=>$code,'err'=>$err,'len'=>is_string($body)?strlen($body):0];
  if ($err || $code<200 || $code>=300) out(502, ['ok'=>false,'error'=>'ElevenLabs échec','dbg'=>$dbg,'body_snippet'=>is_string($body)?substr($body,0,400):'']);
  file_put_contents($file, $body);
  out(200, ['ok'=>true,'mp3'=>"tts/diag/".basename($file),'dbg'=>$dbg]);
}

if ($provider === 'openai') {
  if (!defined('OPENAI_API_KEY') || OPENAI_API_KEY === '') out(400, ['ok'=>false,'error'=>'OPENAI_API_KEY absente (ENV).','dbg'=>$dbg]);
  $v = strtolower(trim($voice ?: 'alloy'));
  $map = ['allow'=>'alloy','aloy'=>'alloy','versa'=>'verse','vèrse'=>'verse'];
  if (isset($map[$v])) $v = $map[$v];

  [$code,$err,$body] = $http('https://api.openai.com/v1/audio/speech', [
    'Authorization' => 'Bearer '.OPENAI_API_KEY,
    'Accept'        => 'audio/mpeg',
    'Content-Type'  => 'application/json'
  ], [
    'model' => 'gpt-4o-mini-tts',
    'input' => $text,
    'voice' => $v,
    'format'=> 'mp3' // (doc OpenAI)
  ]);
  $dbg['http'] = ['code'=>$code,'err'=>$err,'len'=>is_string($body)?strlen($body):0];
  if ($err || $code<200 || $code>=300) out(502, ['ok'=>false,'error'=>'OpenAI TTS échec','dbg'=>$dbg,'body_snippet'=>is_string($body)?substr($body,0,400):'']);
  file_put_contents($file, $body);
  out(200, ['ok'=>true,'mp3'=>"tts/diag/".basename($file),'dbg'=>$dbg]);
}

out(400, ['ok'=>false,'error'=>'provider inconnu (elevenlabs|openai)','dbg'=>$dbg]);
