<?php
/**
 * Telegram and WhatsApp voice/audio transcription adapter.
 */

defined( 'ABSPATH' ) || exit;

class Niwa_AI_Admin_Autonomy_Telegram_Voice_Transcriber {

    private $telegram;
    private $whatsapp;
    private $chat_agent;

    public function __construct( $telegram = null, $whatsapp = null, $chat_agent = null ) {
        $this->telegram   = $telegram;
        $this->whatsapp   = $whatsapp;
        $this->chat_agent = $chat_agent;
    }

    public function transcribe( $ref ) {
        $ref     = is_array( $ref ) ? $ref : array();
        $channel = isset( $ref['channel'] ) ? sanitize_key( (string) $ref['channel'] ) : 'telegram';
        $cleanup = false;

        if ( 'whatsapp' === $channel ) {
            if ( ! $this->whatsapp || ! method_exists( $this->whatsapp, 'resolve_local_media_path' ) ) {
                return array(
                    'success' => false,
                    'text'    => '',
                    'error'   => 'WhatsApp media resolver is not available for transcription.',
                );
            }
            $tmp = $this->whatsapp->resolve_local_media_path( (string) ( $ref['local_path'] ?? '' ) );
            if ( '' === $tmp ) {
                return array(
                    'success' => false,
                    'text'    => '',
                    'error'   => 'WhatsApp audio file is missing or outside the media directory.',
                );
            }
        } else {
            if ( ! $this->telegram || ! method_exists( $this->telegram, 'resolve_file_url' ) || empty( $ref['file_id'] ) ) {
                return array(
                    'success' => false,
                    'text'    => '',
                    'error'   => 'Telegram audio reference is not available for transcription.',
                );
            }
            $file = $this->telegram->resolve_file_url( (string) $ref['file_id'] );
            if ( empty( $file['success'] ) || empty( $file['file_url'] ) ) {
                return array(
                    'success' => false,
                    'text'    => '',
                    'error'   => 'Telegram file resolve failed: '
                        . ( isset( $file['error'] ) ? (string) $file['error'] : 'unknown' ),
                );
            }

            $tmp = Niwa_AI_Admin_Autonomy_Audio_Utils::download_to_temp_with_retry( $file['file_url'] );
            if ( is_wp_error( $tmp ) ) {
                return array(
                    'success' => false,
                    'text'    => '',
                    'error'   => 'Audio download failed: ' . $tmp->get_error_message(),
                );
            }
            $cleanup = true;
        }

        try {
            $valid = Niwa_AI_Admin_Autonomy_Audio_Utils::validate_for_transcription( $tmp );
            if ( is_wp_error( $valid ) ) {
                return array(
                    'success' => false,
                    'text'    => '',
                    'error'   => $valid->get_error_message(),
                );
            }

            if ( ! $this->chat_agent ) {
                return array(
                    'success' => false,
                    'text'    => '',
                    'error'   => 'Chat agent is not available for transcription.',
                );
            }

            $openai_client = $this->chat_agent->get_openai_client_instance();
            if ( ! $openai_client ) {
                return array(
                    'success' => false,
                    'text'    => '',
                    'error'   => 'OpenAI client is not available for transcription.',
                );
            }

            $api_key = $this->chat_agent->get_api_key_direct();
            if ( '' === $api_key ) {
                return array(
                    'success' => false,
                    'text'    => '',
                    'error'   => 'OpenAI API key je potreban za audio transkripciju. Codex OAuth nije podrzan za Whisper API.',
                );
            }

            return $openai_client->transcribe_audio( $tmp, 'api_key', array( 'api_key' => $api_key ) );
        } finally {
            if ( $cleanup && is_file( $tmp ) ) {
                @unlink( $tmp );
            }
        }
    }
}
