<?php
/**
 * AI API Helper Class (Legacy - Backward Compatibility)
 * 
 * This file provides backward compatibility for old code.
 * New code should use: AIAutotool_AI_Helper from ai-providers module
 * 
 * Migration: AIAutotool_API_Helper::openai_chat() → AIAutotool_AI_Helper::generate()
 */

if ( ! defined( 'ABSPATH' ) ) exit; // Thoát nếu truy cập trực tiếp

class AIAutotool_API_Helper {
    
    /**
     * Call OpenAI Chat Completion API
     * 
     * @param string $prompt The prompt to send
     * @param array $options Additional options
     * @return array|WP_Error Response or error
     */
    public static function openai_chat($prompt, $options = array()) {
        $api_key = AIAutotool_API_Manager::get_openai_key();
        
        if (empty($api_key)) {
            return new WP_Error('no_api_key', __('OpenAI API Key is not configured', 'ai-auto-tool'));
        }

        $defaults = array(
            'model' => 'gpt-3.5-turbo',
            'temperature' => 0.7,
            'max_tokens' => 1000,
            'system_message' => 'You are a helpful assistant.'
        );

        $options = wp_parse_args($options, $defaults);

        $messages = array();
        
        if (!empty($options['system_message'])) {
            $messages[] = array(
                'role' => 'system',
                'content' => $options['system_message']
            );
        }

        $messages[] = array(
            'role' => 'user',
            'content' => $prompt
        );

        $body = array(
            'model' => $options['model'],
            'messages' => $messages,
            'temperature' => $options['temperature'],
            'max_tokens' => $options['max_tokens']
        );

        $response = wp_remote_post('https://api.openai.com/v1/chat/completions', array(
            'headers' => array(
                'Authorization' => 'Bearer ' . $api_key,
                'Content-Type' => 'application/json',
            ),
            'body' => json_encode($body),
            'timeout' => 60,
        ));

        if (is_wp_error($response)) {
            return $response;
        }

        $status_code = wp_remote_retrieve_response_code($response);
        $body = json_decode(wp_remote_retrieve_body($response), true);

        if ($status_code !== 200) {
            $error_message = isset($body['error']['message']) ? $body['error']['message'] : 'Unknown error';
            return new WP_Error('api_error', $error_message);
        }

        return array(
            'success' => true,
            'content' => isset($body['choices'][0]['message']['content']) ? $body['choices'][0]['message']['content'] : '',
            'usage' => isset($body['usage']) ? $body['usage'] : array(),
            'model' => isset($body['model']) ? $body['model'] : '',
            'raw_response' => $body
        );
    }

    /**
     * Call Gemini Generate Content API
     * 
     * @param string $prompt The prompt to send
     * @param array $options Additional options
     * @return array|WP_Error Response or error
     */
    public static function gemini_generate($prompt, $options = array()) {
        $api_key = AIAutotool_API_Manager::get_gemini_key();
        
        if (empty($api_key)) {
            return new WP_Error('no_api_key', __('Gemini API Key is not configured', 'ai-auto-tool'));
        }

        $defaults = array(
            'model' => 'gemini-2.5-pro',
            'temperature' => 0.7,
            'max_tokens' => 8192,  // Max for Gemini 2.5 Pro
        );

        $options = wp_parse_args($options, $defaults);

        $url = 'https://generativelanguage.googleapis.com/v1beta/models/' . $options['model'] . ':generateContent?key=' . $api_key;

        $body = array(
            'contents' => array(
                array(
                    'parts' => array(
                        array('text' => $prompt)
                    )
                )
            ),
            'generationConfig' => array(
                'temperature' => $options['temperature'],
                'maxOutputTokens' => $options['max_tokens'],
            )
        );

        $response = wp_remote_post($url, array(
            'headers' => array(
                'Content-Type' => 'application/json',
            ),
            'body' => json_encode($body),
            'timeout' => 60,
        ));

        if (is_wp_error($response)) {
            return $response;
        }

        $status_code = wp_remote_retrieve_response_code($response);
        $response_body = json_decode(wp_remote_retrieve_body($response), true);

        if ($status_code !== 200) {
            $error_message = isset($response_body['error']['message']) ? $response_body['error']['message'] : 'Unknown error';
            return new WP_Error('api_error', $error_message);
        }

        // AGGRESSIVE DEBUG: Log entire response structure
        if (isset($response_body['candidates'][0])) {
            if (isset($response_body['candidates'][0]['content'])) {
            }
            if (isset($response_body['candidates'][0]['finishReason'])) {
            }
        }

        $content = '';
        if (isset($response_body['candidates'][0]['content']['parts'][0]['text'])) {
            $content = $response_body['candidates'][0]['content']['parts'][0]['text'];
        } else {
        }

        return array(
            'success' => true,
            'content' => $content,
            'model' => $options['model'],
            'raw_response' => $response_body
        );
    }

    /**
     * Generate text using available AI (OpenAI or Gemini)
     * 
     * @param string $prompt The prompt
     * @param string $preferred_provider 'openai' or 'gemini'
     * @param array $options Additional options
     * @return array|WP_Error
     */
    public static function generate_text($prompt, $preferred_provider = 'openai', $options = array()) {
        if ($preferred_provider === 'openai') {
            $result = self::openai_chat($prompt, $options);
            
            // Fallback to Gemini if OpenAI fails
            if (is_wp_error($result) && $result->get_error_code() === 'no_api_key') {
                $result = self::gemini_generate($prompt, $options);
            }
        } else {
            $result = self::gemini_generate($prompt, $options);
            
            // Fallback to OpenAI if Gemini fails
            if (is_wp_error($result) && $result->get_error_code() === 'no_api_key') {
                $result = self::openai_chat($prompt, $options);
            }
        }

        return $result;
    }

    /**
     * Generate image using OpenAI DALL-E
     * 
     * @param string $prompt The image description
     * @param array $options Additional options
     * @return array|WP_Error
     */
    public static function openai_generate_image($prompt, $options = array()) {
        $api_key = AIAutotool_API_Manager::get_openai_key();
        
        if (empty($api_key)) {
            return new WP_Error('no_api_key', __('OpenAI API Key is not configured', 'ai-auto-tool'));
        }

        $defaults = array(
            'model' => 'dall-e-3',
            'size' => '1024x1024',
            'quality' => 'standard',
            'n' => 1
        );

        $options = wp_parse_args($options, $defaults);

        $body = array(
            'model' => $options['model'],
            'prompt' => $prompt,
            'size' => $options['size'],
            'quality' => $options['quality'],
            'n' => $options['n']
        );

        $response = wp_remote_post('https://api.openai.com/v1/images/generations', array(
            'headers' => array(
                'Authorization' => 'Bearer ' . $api_key,
                'Content-Type' => 'application/json',
            ),
            'body' => json_encode($body),
            'timeout' => 120,
        ));

        if (is_wp_error($response)) {
            return $response;
        }

        $status_code = wp_remote_retrieve_response_code($response);
        $response_body = json_decode(wp_remote_retrieve_body($response), true);

        if ($status_code !== 200) {
            $error_message = isset($response_body['error']['message']) ? $response_body['error']['message'] : 'Unknown error';
            return new WP_Error('api_error', $error_message);
        }

        return array(
            'success' => true,
            'images' => isset($response_body['data']) ? $response_body['data'] : array(),
            'raw_response' => $response_body
        );
    }

    /**
     * Transcribe audio using OpenAI Whisper
     * 
     * @param string $audio_file_path Path to audio file
     * @param array $options Additional options
     * @return array|WP_Error
     */
    public static function openai_transcribe_audio($audio_file_path, $options = array()) {
        $api_key = AIAutotool_API_Manager::get_openai_key();
        
        if (empty($api_key)) {
            return new WP_Error('no_api_key', __('OpenAI API Key is not configured', 'ai-auto-tool'));
        }

        if (!file_exists($audio_file_path)) {
            return new WP_Error('file_not_found', __('Audio file not found', 'ai-auto-tool'));
        }

        $defaults = array(
            'model' => 'whisper-1',
            'language' => '',
            'response_format' => 'json'
        );

        $options = wp_parse_args($options, $defaults);

        $boundary = wp_generate_password(24);
        $file_contents = file_get_contents($audio_file_path);
        $filename = basename($audio_file_path);

        $body = "--{$boundary}\r\n";
        $body .= "Content-Disposition: form-data; name=\"file\"; filename=\"{$filename}\"\r\n";
        $body .= "Content-Type: audio/mpeg\r\n\r\n";
        $body .= $file_contents . "\r\n";
        $body .= "--{$boundary}\r\n";
        $body .= "Content-Disposition: form-data; name=\"model\"\r\n\r\n";
        $body .= $options['model'] . "\r\n";

        if (!empty($options['language'])) {
            $body .= "--{$boundary}\r\n";
            $body .= "Content-Disposition: form-data; name=\"language\"\r\n\r\n";
            $body .= $options['language'] . "\r\n";
        }

        $body .= "--{$boundary}--\r\n";

        $response = wp_remote_post('https://api.openai.com/v1/audio/transcriptions', array(
            'headers' => array(
                'Authorization' => 'Bearer ' . $api_key,
                'Content-Type' => 'multipart/form-data; boundary=' . $boundary,
            ),
            'body' => $body,
            'timeout' => 120,
        ));

        if (is_wp_error($response)) {
            return $response;
        }

        $status_code = wp_remote_retrieve_response_code($response);
        $response_body = json_decode(wp_remote_retrieve_body($response), true);

        if ($status_code !== 200) {
            $error_message = isset($response_body['error']['message']) ? $response_body['error']['message'] : 'Unknown error';
            return new WP_Error('api_error', $error_message);
        }

        return array(
            'success' => true,
            'text' => isset($response_body['text']) ? $response_body['text'] : '',
            'raw_response' => $response_body
        );
    }

    /**
     * Check if OpenAI is configured
     * 
     * @return bool
     */
    public static function is_openai_configured() {
        $api_key = AIAutotool_API_Manager::get_openai_key();
        return !empty($api_key);
    }

    /**
     * Check if Gemini is configured
     * 
     * @return bool
     */
    public static function is_gemini_configured() {
        $api_key = AIAutotool_API_Manager::get_gemini_key();
        return !empty($api_key);
    }

    /**
     * Check if any AI provider is configured
     * 
     * @return bool
     */
    public static function is_any_ai_configured() {
        return self::is_openai_configured() || self::is_gemini_configured();
    }

    /**
     * Get available AI providers
     * 
     * @return array
     */
    public static function get_available_providers() {
        $providers = array();

        if (self::is_openai_configured()) {
            $providers[] = 'openai';
        }

        if (self::is_gemini_configured()) {
            $providers[] = 'gemini';
        }

        return $providers;
    }

    /**
     * Format AI response for display
     * 
     * @param array|WP_Error $response
     * @return string
     */
    public static function format_response($response) {
        if (is_wp_error($response)) {
            return '[Error: ' . $response->get_error_message() . ']';
        }

        if (isset($response['content'])) {
            return $response['content'];
        }

        return '[No content returned]';
    }

    /**
     * Log AI API usage
     * 
     * @param string $provider 'openai' or 'gemini'
     * @param array $usage_data
     */
    public static function log_usage($provider, $usage_data) {
        $logs = get_option('aiautotool_api_usage_logs', array());
        
        $logs[] = array(
            'provider' => $provider,
            'timestamp' => current_time('mysql'),
            'usage' => $usage_data
        );

        // Keep only last 100 logs
        if (count($logs) > 100) {
            $logs = array_slice($logs, -100);
        }

        update_option('aiautotool_api_usage_logs', $logs, false);
    }

    /**
     * Get usage statistics
     * 
     * @return array
     */
    public static function get_usage_stats() {
        $logs = get_option('aiautotool_api_usage_logs', array());
        
        $stats = array(
            'total_requests' => count($logs),
            'openai_requests' => 0,
            'gemini_requests' => 0,
            'total_tokens' => 0
        );

        foreach ($logs as $log) {
            if ($log['provider'] === 'openai') {
                $stats['openai_requests']++;
                if (isset($log['usage']['total_tokens'])) {
                    $stats['total_tokens'] += $log['usage']['total_tokens'];
                }
            } elseif ($log['provider'] === 'gemini') {
                $stats['gemini_requests']++;
            }
        }

        return $stats;
    }
}

