<?php
ob_start();

error_reporting(E_ALL);
ini_set('display_errors', 0);

header('Content-Type: application/json; charset=utf-8');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type');

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    ob_end_clean();
    http_response_code(204);
    exit;
}

try {
    $rawInput = file_get_contents('php://input');
    $data = json_decode($rawInput, true);
    if (!$data) {
        $data = $_POST;
    }

    $text = trim($data['text'] ?? '');
    $voice = trim($data['voice'] ?? 'charles');
    $speed = floatval($data['speed'] ?? 1.0);
    $emotion = trim($data['emotion'] ?? 'warm');

    if (empty($text)) {
        throw new Exception('text is empty');
    }

    if (mb_strlen($text) > 2000) {
        $text = mb_substr($text, 0, 2000);
    }

    $voiceMap = [
        'alex'     => 'FunAudioLLM/CosyVoice2-0.5B:alex',
        'benjamin' => 'FunAudioLLM/CosyVoice2-0.5B:benjamin',
        'charles'  => 'FunAudioLLM/CosyVoice2-0.5B:charles',
        'david'    => 'FunAudioLLM/CosyVoice2-0.5B:david',
        'anna'     => 'FunAudioLLM/CosyVoice2-0.5B:anna',
        'bella'    => 'FunAudioLLM/CosyVoice2-0.5B:bella',
        'claire'   => 'FunAudioLLM/CosyVoice2-0.5B:claire',
        'diana'    => 'FunAudioLLM/CosyVoice2-0.5B:diana',
    ];

    $emotionSpeedMap = [
        'warm'    => 0.95,
        'excited' => 1.15,
        'romantic'=> 0.85,
        'solemn'  => 0.9,
        'joyful'  => 1.1,
        'quiet'   => 0.8,
    ];

    $voiceId = $voiceMap[$voice] ?? $voiceMap['charles'];
    $finalSpeed = $speed * ($emotionSpeedMap[$emotion] ?? 1.0);
    $finalSpeed = max(0.25, min(4.0, $finalSpeed));

    $apiKey = 'sk-bcczdchfdqzvrdcaozkubiypsmgathqotfsdgjshowosyumg';
    $apiUrl = 'https://api.siliconflow.cn/v1/audio/speech';

    $payload = json_encode([
        'model' => 'FunAudioLLM/CosyVoice2-0.5B',
        'input' => $text,
        'voice' => $voiceId,
        'response_format' => 'mp3',
        'speed' => $finalSpeed,
        'sample_rate' => 44100,
    ]);

    $ch = curl_init($apiUrl);
    if ($ch === false) {
        throw new Exception('curl_init failed');
    }

    curl_setopt_array($ch, [
        CURLOPT_POST => true,
        CURLOPT_POSTFIELDS => $payload,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_TIMEOUT => 60,
        CURLOPT_CONNECTTIMEOUT => 10,
        CURLOPT_SSL_VERIFYPEER => false,
        CURLOPT_SSL_VERIFYHOST => false,
        CURLOPT_HTTPHEADER => [
            'Authorization: Bearer ' . $apiKey,
            'Content-Type: application/json',
        ],
    ]);

    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $curlError = curl_error($ch);
    $contentType = curl_getinfo($ch, CURLINFO_CONTENT_TYPE);
    curl_close($ch);

    if ($curlError) {
        throw new Exception('curl error: ' . $curlError);
    }

    if ($httpCode !== 200) {
        $errBody = mb_substr($response, 0, 300);
        throw new Exception('API returned HTTP ' . $httpCode . ': ' . $errBody);
    }

    $audioDir = __DIR__ . '/../tts_cache';
    if (!is_dir($audioDir)) {
        mkdir($audioDir, 0755, true);
    }

    $filename = 'tts_' . md5($text . $voice . $speed . $emotion) . '.mp3';
    $filepath = $audioDir . '/' . $filename;
    file_put_contents($filepath, $response);

    ob_end_clean();

    echo json_encode([
        'success' => true,
        'audio_url' => 'tts_cache/' . $filename,
        'voice' => $voice,
        'size' => strlen($response)
    ]);

} catch (Exception $e) {
    ob_end_clean();
    echo json_encode([
        'success' => false,
        'message' => $e->getMessage()
    ]);
}
