<?php
if (!defined('ABSPATH')) {
    exit;
}

/**
 * OpenAI Platformvider
 *
 * Implements the AI Platformvider Interface for OpenAI.
 *
 * @package    Kitsune_AI_Platform
 * @subpackage Kitsune_AI_Platform/includes/api/providers
 */
class Kitsune_AI_Platform_OpenAI_Provider implements Kitsune_AI_Platform_Provider_Interface {

    private $api_key;
    private $api_url = 'https://api.openai.com/v1/';

    public function __construct($api_key) {
        $this->api_key = $api_key;
    }

    public function chat($params) {
        $endpoint = $this->api_url . 'chat/completions';
        $timeout = max(1, (int) apply_filters('kitsune_ai_platform_api_timeout', 60, 'openai'));
        
        $model = $params['model'] ?? KITSUNE_AI_PLATFORM_DEFAULT_MODEL;
        $body = array(
            'model'    => $model,
            'messages' => $params['messages'],
        );

        if (in_array($model, KITSUNE_AI_PLATFORM_OPENAI_STANDARD_MODELS, true)) {
            foreach (KITSUNE_AI_PLATFORM_OPENAI_STANDARD_OPTIONS as $option) {
                $key = $option['key'];
                if (isset($params[$key])) {
                    $body[$key] = $params[$key];
                }
            }
        } elseif (array_key_exists($model, KITSUNE_AI_PLATFORM_OPENAI_REASONING_MODELS)) {
            $allowed_efforts = KITSUNE_AI_PLATFORM_OPENAI_REASONING_MODELS[$model];
            if (is_array($allowed_efforts) && !empty($params['reasoning_effort']) && in_array($params['reasoning_effort'], $allowed_efforts, true)) {
                $body['reasoning_effort'] = $params['reasoning_effort'];
            }
        }

        $response = wp_remote_post($endpoint, array(
            'headers' => array(
                'Authorization' => 'Bearer ' . $this->api_key,
                'Content-Type'  => 'application/json',
            ),
            'body'    => wp_json_encode($body),
            'timeout' => $timeout,
        ));

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

        $code = wp_remote_retrieve_response_code($response);
        $body_response = json_decode(wp_remote_retrieve_body($response), true);

        if ($code !== 200) {
            return array(
                'success' => false,
                'message' => $body_response['error']['message'] ?? __('OpenAI API Error', 'kitsune-ai-platform'),
            );
        }

        return array(
            'success' => true,
            'data'    => array(
                'content' => $body_response['choices'][0]['message']['content'] ?? '',
                'usage'   => $body_response['usage'] ?? array(),
            ),
        );
    }

    public function validate_key($api_key) {
        // Quick model list check
        $timeout = max(1, (int) apply_filters('kitsune_ai_platform_api_timeout', 60, 'openai'));
        $response = wp_remote_get($this->api_url . 'models', array(
            'headers' => array(
                'Authorization' => 'Bearer ' . $api_key,
            ),
            'timeout' => $timeout,
        ));

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

        $code = wp_remote_retrieve_response_code($response);
        $body_response = json_decode(wp_remote_retrieve_body($response), true);

        if ($code === 200) {
            return array(
                'success' => true,
                'message' => __('Connected successfully to OpenAI', 'kitsune-ai-platform'),
            );
        }

        $error_msg = $body_response['error']['message'] ?? current( (array) $body_response['error'] ) ?? __('Invalid API Key', 'kitsune-ai-platform');

        return array(
            'success' => false,
            'message' => $error_msg,
        );
    }

    public function embed($params) {
        $endpoint = $this->api_url . 'embeddings';
        $timeout = max(1, (int) apply_filters('kitsune_ai_platform_api_timeout', 60, 'openai'));

        $input = $params['input'] ?? '';
        $model = $params['model'] ?? 'text-embedding-3-small';

        if (!is_string($input) || $input === '') {
            return array(
                'success' => false,
                'message' => __('Embedding input is required.', 'kitsune-ai-platform'),
            );
        }

        $body = array(
            'model' => $model,
            'input' => $input,
        );

        $response = wp_remote_post($endpoint, array(
            'headers' => array(
                'Authorization' => 'Bearer ' . $this->api_key,
                'Content-Type' => 'application/json',
            ),
            'body' => wp_json_encode($body),
            'timeout' => $timeout,
        ));

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

        $code = wp_remote_retrieve_response_code($response);
        $body_response = json_decode(wp_remote_retrieve_body($response), true);

        if ($code !== 200) {
            return array(
                'success' => false,
                'message' => $body_response['error']['message'] ?? __('OpenAI embedding API error', 'kitsune-ai-platform'),
            );
        }

        $vector = $body_response['data'][0]['embedding'] ?? null;
        if (!is_array($vector) || empty($vector)) {
            return array(
                'success' => false,
                'message' => __('OpenAI embedding response missing vector.', 'kitsune-ai-platform'),
            );
        }

        return array(
            'success' => true,
            'data' => array(
                'embedding' => $vector,
                'usage' => $body_response['usage'] ?? array(),
            ),
        );
    }

    public function generate_image($prompt, $params) {
        $endpoint = $this->api_url . 'images/generations';
        $timeout  = max(1, (int) apply_filters('kitsune_ai_platform_api_timeout', 120, 'openai'));

        $model   = sanitize_text_field($params['model'] ?? 'dall-e-3');
        $style   = sanitize_text_field($params['style'] ?? '');
        $quality = sanitize_text_field($params['quality'] ?? 'standard');
        $aspect  = sanitize_text_field($params['aspect_ratio'] ?? '1:1');

        $size_map = array(
            '1:1'  => '1024x1024',
            '16:9' => '1792x1024',
            '9:16' => '1024x1792',
        );
        $size = $size_map[$aspect] ?? '1024x1024';

        $body = array(
            'model'           => $model,
            'prompt'          => $prompt,
            'n'               => 1,
            'size'            => $size,
            'response_format' => 'url',
        );

        if ($model === 'dall-e-3' && in_array($style, array('vivid', 'natural'), true)) {
            $body['style'] = $style;
        }

        if ($model === 'dall-e-3' && in_array($quality, array('standard', 'hd'), true)) {
            $body['quality'] = $quality;
        }

        $response = wp_remote_post($endpoint, array(
            'headers' => array(
                'Authorization' => 'Bearer ' . $this->api_key,
                'Content-Type'  => 'application/json',
            ),
            'body'    => wp_json_encode($body),
            'timeout' => $timeout,
        ));

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

        $code          = wp_remote_retrieve_response_code($response);
        $body_response = json_decode(wp_remote_retrieve_body($response), true);

        if ($code !== 200) {
            return array(
                'success' => false,
                'message' => $body_response['error']['message'] ?? __('OpenAI image generation error', 'kitsune-ai-platform'),
            );
        }

        $url = $body_response['data'][0]['url'] ?? '';
        if ($url === '') {
            return array(
                'success' => false,
                'message' => __('OpenAI returned no image URL.', 'kitsune-ai-platform'),
            );
        }

        return array(
            'success' => true,
            'data'    => array(
                'url'      => $url,
                'model'    => $model,
                'provider' => 'openai',
            ),
        );
    }
}
