<?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);

$overrides = [];
if ($weckerId > 0) {
    $wecker = function_wecker_hole($weckerId);
    if ($wecker) {
        if ($text === '') {
            $text = trim($wecker['sprachtext'] ?? '');
        }
        if (!empty($wecker['weckzeit'])) {
            $overrides['weckzeit'] = substr($wecker['weckzeit'], 0, 5);
        }
    }
}

if ($text === '') {
    function_json_antwort(false, [], 'Text fehlt');
}
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_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.');
