<?php
namespace EasyChat\Library\Voice;

 
class VoiceMessageTextResolver {
    public const TRANSCRIPT_MARKER = '[Слова клиента из голосового сообщения — уже распознаны в текст]';

    private $db;
    private $prefix;

    public function __construct($registry) {
        $this->db = $registry->get('db');
        $this->prefix = easychat_db_prefix();
    }

     
    public function transcriptsForRows(array $rows): array {
        $ids = [];
        foreach ($rows as $row) {
            $id = (int)($row['message_id'] ?? 0);
            if ($id > 0) $ids[$id] = $id;
        }
        if (!$ids) return [];

        $query = $this->db->query(
            "SELECT `message_id`, `meta_json` FROM `{$this->prefix}message_attachments` "
            . "WHERE `message_id` IN (" . implode(',', array_values($ids)) . ") ORDER BY `id` ASC"
        );
        $parts = [];
        foreach ((array)$query->rows as $row) {
            $meta = json_decode((string)($row['meta_json'] ?? ''), true);
            $transcription = is_array($meta['voice']['transcription'] ?? null)
                ? $meta['voice']['transcription']
                : [];
            $text = trim((string)($transcription['text'] ?? ''));
            $message_id = (int)($row['message_id'] ?? 0);
            if (($transcription['status'] ?? '') === 'ready' && $text !== '' && $message_id > 0) {
                $parts[$message_id][] = $text;
            }
        }

        $result = [];
        foreach ($parts as $message_id => $texts) {
            $result[(int)$message_id] = implode("\n", $texts);
        }
        return $result;
    }

    public function compose(array $row, array $transcripts): string {
        $text = trim(urldecode((string)($row['text'] ?? '')));
        $transcript = trim((string)($transcripts[(int)($row['message_id'] ?? 0)] ?? ''));
        if ($transcript === '') return $text;

         
         
        $voice = self::TRANSCRIPT_MARKER . "\n" . $transcript;
        return $text !== '' ? $text . "\n\n" . $voice : $voice;
    }
}
