<?php
/**
 * API handler for communicating with OpenAI
 */
class Nietos_AI_API_Handler {

    /**
     * Security instance
     */
    private $security;

    /**
     * Constructor
     */
    public function __construct($security) {
        $this->security = $security;
    }

    /**
     * Send message to OpenAI
     */
    public function send_message($messages, $settings, $tools = null) {
        $api_key = $settings['api_key'] ?? '';

        if (empty($api_key)) {
            return new WP_Error('no_api_key', __('API key not configured', 'nietos-ai'));
        }

        // Decrypt API key
        $api_key = $this->security->decrypt_api_key($api_key);

        return $this->send_openai_message($messages, $settings, $api_key, $tools);
    }

    /**
     * Send message to OpenAI API
     */
    private function send_openai_message($messages, $settings, $api_key, $tools) {
        $model = $settings['model'] ?? 'gpt-4o';
        $max_tokens = $settings['max_tokens'] ?? 4096;
        $temperature = $settings['temperature'] ?? 0.7;

        // Lower temperature when using tools for more consistent behavior
        if (!empty($tools)) {
            $temperature = min($temperature, 0.3);
        }

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

        if (!empty($tools)) {
            $body['tools'] = $tools;
            $body['tool_choice'] = 'auto';
            $body['parallel_tool_calls'] = false; // Execute tools one at a time
        }

        $response = wp_remote_post('https://api.openai.com/v1/chat/completions', array(
            'headers' => array(
                'Content-Type' => 'application/json',
                'Authorization' => 'Bearer ' . $api_key
            ),
            'body' => json_encode($body),
            'timeout' => 120, // Increased from 60 to 120 seconds for complex requests with tools
            'sslverify' => true
        ));

        // Log request for debugging
        if (defined('NIETOS_AI_DEBUG') && NIETOS_AI_DEBUG) {
            error_log('OpenAI API Request: ' . json_encode(array(
                'model' => $model,
                'tools_count' => !empty($tools) ? count($tools) : 0,
                'messages_count' => count($messages)
            )));
        }

        if (is_wp_error($response)) {
            $error_code = $response->get_error_code();
            $error_message = $response->get_error_message();

            // Log timeout errors
            if (defined('NIETOS_AI_DEBUG') && NIETOS_AI_DEBUG) {
                error_log('OpenAI API Error: ' . $error_code . ' - ' . $error_message);
            }

            // Provide more helpful error message for timeouts
            if (strpos($error_message, 'timed out') !== false || strpos($error_message, 'timeout') !== false) {
                return new WP_Error(
                    'timeout_error',
                    __('Request timed out. OpenAI API took too long to respond. This can happen with complex requests. Try again or consider using a faster model like GPT-4o Mini.', 'nietos-ai')
                );
            }

            return $response;
        }

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

        // Log response for debugging
        if (defined('NIETOS_AI_DEBUG') && NIETOS_AI_DEBUG) {
            if (isset($response_body['choices'][0]['message'])) {
                $msg = $response_body['choices'][0]['message'];
                $content_preview = '';
                if (!empty($msg['content'])) {
                    $content_preview = mb_substr($msg['content'], 0, 100);
                    if (mb_strlen($msg['content']) > 100) {
                        $content_preview .= '...';
                    }
                }

                error_log('OpenAI Response: ' . json_encode(array(
                    'has_content' => !empty($msg['content']),
                    'content_length' => !empty($msg['content']) ? strlen($msg['content']) : 0,
                    'content_preview' => $content_preview,
                    'has_tool_calls' => !empty($msg['tool_calls']),
                    'tool_calls_count' => !empty($msg['tool_calls']) ? count($msg['tool_calls']) : 0,
                    'finish_reason' => $response_body['choices'][0]['finish_reason'] ?? 'unknown'
                )));

                // Log tool calls if present
                if (!empty($msg['tool_calls'])) {
                    foreach ($msg['tool_calls'] as $idx => $tc) {
                        error_log("  Tool call " . ($idx + 1) . ": " . ($tc['function']['name'] ?? 'unknown'));
                    }
                }
            }
        }

        if ($status_code !== 200) {
            $error_message = $response_body['error']['message'] ?? 'Unknown error';
            error_log('OpenAI API Error (' . $status_code . '): ' . json_encode($response_body));
            return new WP_Error('api_error', $error_message);
        }

        return $response_body;
    }

    /**
     * Test API connection
     */
    public function test_connection($api_key, $model) {
        $decrypted_key = $this->security->decrypt_api_key($api_key);

        $test_messages = array(
            array(
                'role' => 'user',
                'content' => 'Hello, this is a test message. Please respond with "OK".'
            )
        );

        $settings = array(
            'api_key' => $api_key,
            'model' => $model,
            'max_tokens' => 100,
            'temperature' => 0.7
        );

        $response = $this->send_message($test_messages, $settings);

        if (is_wp_error($response)) {
            return array(
                'success' => false,
                'message' => $response->get_error_message()
            );
        }

        return array(
            'success' => true,
            'message' => __('Connection successful!', 'nietos-ai')
        );
    }
}
