<?php
/**
 * Azure OpenAI Provider
 */

if ( ! defined( 'ABSPATH' ) ) exit;

class AIAutotool_AI_Provider_Azure_OpenAI extends AIAutotool_AI_Provider_Base {
    protected $name = 'Azure OpenAI';
    protected $id = 'azure_openai';
    protected $base_url = '';
    protected $default_model = 'azure-deployment';
    protected $available_models = array(
        'azure-deployment' => 'Configured Azure Deployment',
    );
    private $api_version = '2024-10-21';

    public function __construct($api_key = '') {
        parent::__construct($api_key);

        if (empty($this->api_key)) {
            $this->api_key = $this->get_rotated_key();
        }
    }

    public function chat_completion($messages, $options = array()) {
        $credentials = $this->parse_credentials($this->api_key);
        if (!$credentials) {
            return array(
                'success' => false,
                'error' => 'Azure OpenAI credentials not configured. Expected: endpoint|deployment|api_key'
            );
        }

        $options = $this->parse_options($options);
        $url = rtrim($credentials['endpoint'], '/') . '/openai/deployments/' . rawurlencode($credentials['deployment']) . '/chat/completions?api-version=' . rawurlencode($this->api_version);
        $body = array(
            'messages' => $messages,
            'max_tokens' => intval($options['max_tokens']),
            'top_p' => floatval($options['top_p'])
        );

        $temperature = floatval($options['temperature']);
        if ($temperature == 1.0) {
            $body['temperature'] = $temperature;
        }

        $response = $this->make_request($url, $body, 'POST', array(
            'api-key' => $credentials['api_key'],
            'Content-Type' => 'application/json'
        ));

        if (!$response['success']) {
            return $response;
        }

        $data = $response['data'];
        if (!isset($data['choices'][0]['message']['content'])) {
            return array(
                'success' => false,
                'error' => 'Invalid response structure: missing message content'
            );
        }

        return array(
            'success' => true,
            'content' => $data['choices'][0]['message']['content'],
            'usage' => isset($data['usage']) ? $data['usage'] : null,
            'model' => $credentials['deployment'],
            'finish_reason' => isset($data['choices'][0]['finish_reason']) ? $data['choices'][0]['finish_reason'] : null
        );
    }

    public function test_connection() {
        $result = $this->chat_completion(array(
            array('role' => 'user', 'content' => 'Reply with OK.')
        ), array(
            'temperature' => 1.0,
            'max_tokens' => 32
        ));

        if ($result['success']) {
            return array(
                'success' => true,
                'message' => 'Azure OpenAI API connection successful!',
                'response' => trim($result['content']),
                'model' => isset($result['model']) ? $result['model'] : $this->default_model,
                'usage' => isset($result['usage']) ? $result['usage'] : null
            );
        }

        return array(
            'success' => false,
            'message' => 'Azure OpenAI API Error: ' . (isset($result['error']) ? $result['error'] : 'Unknown error')
        );
    }

    public function get_models() {
        return array(
            'success' => true,
            'models' => array_keys($this->available_models)
        );
    }

    private function parse_credentials($value) {
        if (empty($value) || strpos($value, '|') === false) {
            return false;
        }

        $parts = array_map('trim', explode('|', $value, 3));
        if (count($parts) !== 3 || empty($parts[0]) || empty($parts[1]) || empty($parts[2])) {
            return false;
        }

        return array(
            'endpoint' => $parts[0],
            'deployment' => $parts[1],
            'api_key' => $parts[2]
        );
    }
}
