<?php
/**
 * API: TTS generieren (Text → Audio). Nutzt konfigurierten Anbieter (Piper oder OpenAI).
 * POST action=generate, text=...  Optional: id=Wecker-ID dann wird sprachtext mit Platzhaltern verwendet.
 */
require __DIR__ . '/../config.php';
require FUNCTIONS_ROOT . '/functions_db.php';
require FUNCTIONS_ROOT . '/functions_wecker.php';
require FUNCTIONS_ROOT . '/functions_common.php';
require FUNCTIONS_ROOT . '/functions_tts.php';

header('Content-Type: application/json; charset=utf-8');

$action = $_POST['action'] ?? $_GET['action'] ?? '';

if ($action !== 'generate') {
    function_json_antwort(false, [], 'Unbekannte Aktion');
}

$text = trim($_POST['text'] ?? '');
$weckerId = isset($_POST['id']) ? (int) $_POST['id'] : (isset($_GET['id']) ? (int) $_GET['id'] : 0);

if ($weckerId > 0 && $text === '') {
    $wecker = function_wecker_hole($weckerId);
    if ($wecker && !empty($wecker['sprachtext'])) {
        $text = $wecker['sprachtext'];
    }
}

if ($text === '') {
    function_json_antwort(false, [], 'Text fehlt');
}

$overrides = [];
if (isset($_POST['tts_provider']) && $_POST['tts_provider'] !== '') {
    $overrides['provider'] = trim((string) $_POST['tts_provider']);
}
if (isset($_POST['tts_modell']) && $_POST['tts_modell'] !== '') {
    $overrides['modell'] = trim((string) $_POST['tts_modell']);
}
if (isset($_POST['tts_openai_model']) && $_POST['tts_openai_model'] !== '') {
    $overrides['openai_model'] = trim((string) $_POST['tts_openai_model']);
}
if (isset($_POST['tts_openai_voice']) && $_POST['tts_openai_voice'] !== '') {
    $overrides['openai_voice'] = trim((string) $_POST['tts_openai_voice']);
}
if (isset($_POST['tts_openai_api_key'])) {
    $overrides['openai_api_key'] = trim((string) $_POST['tts_openai_api_key']);
}
if (isset($_POST['tts_openai_speed']) && $_POST['tts_openai_speed'] !== '') {
    $overrides['openai_speed'] = trim((string) $_POST['tts_openai_speed']);
}
if (isset($_POST['tts_openai_response_format']) && $_POST['tts_openai_response_format'] !== '') {
    $overrides['openai_response_format'] = trim((string) $_POST['tts_openai_response_format']);
}
if (isset($_POST['tts_openai_instructions'])) {
    $overrides['openai_instructions'] = trim((string) $_POST['tts_openai_instructions']);
}

$result = function_tts_generieren($text, null, $overrides);
if (!empty($result['ok'])) {
    function_json_antwort(true, ['url' => $result['url'], 'file' => $result['file'] ?? '']);
}

function_json_antwort(false, [], $result['error'] ?? 'TTS-Generierung fehlgeschlagen.');
