<?php
/**
 * TTS-Cache: ersetzter Text → Audio-Dateiname.
 * Verhindert doppelte TTS-Erzeugung bei gleichem Text (z.B. "Guten Morgen Lucas, es ist 7 Uhr 00...").
 */
if (!defined('FUNCTIONS_ROOT')) {
    return;
}

require_once __DIR__ . '/functions_common.php';

function function_tts_occurrence_map_path(): string
{
    return (defined('STORAGE_ROOT') ? STORAGE_ROOT : (dirname(APP_ROOT) . '/storage')) . '/tts_occurrences.json';
}

function function_tts_occurrence_key(int $weckerId, DateTimeInterface $ringZeit): string
{
    return $weckerId . '|' . $ringZeit->format('Y-m-d H:i');
}

function function_tts_occurrence_read_map(): array
{
    $path = function_tts_occurrence_map_path();
    if (!is_file($path)) {
        return [];
    }
    $raw = @file_get_contents($path);
    if ($raw === false || trim($raw) === '') {
        return [];
    }
    $data = @json_decode($raw, true);
    return is_array($data) ? $data : [];
}

function function_tts_occurrence_write_map(array $map): bool
{
    $path = function_tts_occurrence_map_path();
    $dir = dirname($path);
    if (!is_dir($dir)) {
        @mkdir($dir, 0755, true);
    }
    return @file_put_contents($path, json_encode($map, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT)) !== false;
}

function function_tts_occurrence_prune(array $map): array
{
    $minTime = time() - 172800;
    foreach ($map as $key => $entry) {
        $createdAt = isset($entry['created_at']) ? strtotime((string) $entry['created_at']) : false;
        if ($createdAt !== false && $createdAt < $minTime) {
            unset($map[$key]);
        }
    }
    return $map;
}

/**
 * Sucht gecachte Audio-Datei für den exakten ersetzten Text.
 * @return string|null Dateiname (z.B. tts_123.mp3) oder null wenn nicht gecacht oder Datei fehlt
 */
function function_tts_cache_get(string $replacedText): ?string
{
    $text = trim($replacedText);
    if ($text === '') {
        return null;
    }
    $hash = hash('sha256', $text);
    $pdo = $GLOBALS['pdo'] ?? null;
    if (!$pdo) {
        return null;
    }
    try {
        $stmt = $pdo->prepare('SELECT audio_dateiname FROM wecker_tts_cache WHERE text_hash = :hash LIMIT 1');
        $stmt->execute(['hash' => $hash]);
        $row = $stmt->fetch(PDO::FETCH_ASSOC);
        if (!$row || empty($row['audio_dateiname'])) {
            return null;
        }
        $filename = $row['audio_dateiname'];
        $ttsDir = function_storage_tts_dir();
        if (!is_file($ttsDir . $filename)) {
            return null;
        }
        return $filename;
    } catch (Throwable $e) {
        return null;
    }
}

/**
 * Speichert ersetzten Text und zugehörige Audio-Datei im Cache.
 */
function function_tts_cache_set(string $replacedText, string $audioDateiname): bool
{
    $text = trim($replacedText);
    if ($text === '' || trim($audioDateiname) === '') {
        return false;
    }
    $hash = hash('sha256', $text);
    $pdo = $GLOBALS['pdo'] ?? null;
    if (!$pdo) {
        return false;
    }
    try {
        $stmt = $pdo->prepare('
            INSERT INTO wecker_tts_cache (text_hash, replaced_text, audio_dateiname)
            VALUES (:hash, :text, :filename)
            ON DUPLICATE KEY UPDATE replaced_text = VALUES(replaced_text), audio_dateiname = VALUES(audio_dateiname), created_at = CURRENT_TIMESTAMP
        ');
        $stmt->execute([
            'hash'     => $hash,
            'text'     => $text,
            'filename' => $audioDateiname,
        ]);
        return true;
    } catch (Throwable $e) {
        return false;
    }
}

function function_tts_occurrence_set(int $weckerId, DateTimeInterface $ringZeit, string $audioDateiname, string $replacedText = ''): bool
{
    $filename = trim($audioDateiname);
    if ($weckerId <= 0 || $filename === '') {
        return false;
    }
    $map = function_tts_occurrence_prune(function_tts_occurrence_read_map());
    $map[function_tts_occurrence_key($weckerId, $ringZeit)] = [
        'audio_dateiname' => basename($filename),
        'replaced_text'   => trim($replacedText),
        'created_at'      => date('c'),
    ];
    return function_tts_occurrence_write_map($map);
}

function function_tts_occurrence_get(int $weckerId, DateTimeInterface $ringZeit): ?array
{
    if ($weckerId <= 0) {
        return null;
    }
    $map = function_tts_occurrence_prune(function_tts_occurrence_read_map());
    $key = function_tts_occurrence_key($weckerId, $ringZeit);
    $entry = $map[$key] ?? null;
    if (!is_array($entry) || empty($entry['audio_dateiname'])) {
        return null;
    }
    $filename = basename((string) $entry['audio_dateiname']);
    if (!is_file(function_storage_tts_dir() . $filename)) {
        return null;
    }
    return [
        'audio_dateiname' => $filename,
        'replaced_text'   => (string) ($entry['replaced_text'] ?? ''),
    ];
}
