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

/**
 * Anthropic Provider
 *
 * Implements the AI Platformvider Interface for Anthropic (Claude).
 *
 * @package    Kitsune_AI_Platform
 * @subpackage Kitsune_AI_Platform/includes/api/providers
 */
class Kitsune_AI_Platform_Anthropic_Provider implements Kitsune_AI_Platform_Provider_Interface {

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

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

    public function chat($params) {
        $timeout = max(1, (int) apply_filters('kitsune_ai_platform_api_timeout', 60, 'anthropic'));

        $model = $params['model'] ?? KITSUNE_AI_PLATFORM_ANTHROPIC_MODELS[0];
        $body = array(
            'model'    => $model,
            'messages' => $params['messages'],
        );

        foreach (KITSUNE_AI_PLATFORM_ANTHROPIC_BASE_OPTIONS as $option) {
            $key = $option['key'];
            if (isset($params[$key])) {
                $body[$key] = $params[$key];
            }
        }

        if (in_array($model, KITSUNE_AI_PLATFORM_ANTHROPIC_EXTENDED_THINKING_MODELS, true)) {
            foreach (KITSUNE_AI_PLATFORM_ANTHROPIC_THINKING_OPTIONS as $option) {
                $key = $option['key'];
                if (isset($params[$key])) {
                    if ($key === 'thinking.budget_tokens') {
                        $body['thinking'] = array(
                            'type'          => 'enabled',
                            'budget_tokens' => (int)$params[$key]
                        );
                    } else {
                        $body[$key] = $params[$key];
                    }
                }
            }
        }

        $response = wp_remote_post($this->api_url, array(
            'headers' => array(
                'x-api-key'         => $this->api_key,
                'anthropic-version' => '2023-06-01',
                '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'] ?? __('Anthropic API Error', 'kitsune-ai-platform'),
            );
        }

        return array(
            'success' => true,
            'data'    => array(
                'content' => $body_response['content'][0]['text'] ?? '',
                'usage'   => array( // Normalize usage
                    'prompt_tokens' => $body_response['usage']['input_tokens'] ?? 0,
                    'completion_tokens' => $body_response['usage']['output_tokens'] ?? 0,
                    'total_tokens' => ($body_response['usage']['input_tokens'] ?? 0) + ($body_response['usage']['output_tokens'] ?? 0)
                ),
            ),
        );
    }

    public function validate_key($api_key) {
        // Checking with a tiny request
        $timeout = max(1, (int) apply_filters('kitsune_ai_platform_api_timeout', 60, 'anthropic'));
        $response = wp_remote_post($this->api_url, array(
            'headers' => array(
                'x-api-key'         => $api_key,
                'anthropic-version' => '2023-06-01',
                'content-type'      => 'application/json',
            ),
            'body' => wp_json_encode(array(
                'model' => KITSUNE_AI_PLATFORM_ANTHROPIC_MODELS[4], // Smallest/cheapest Anthropic model for validation ping
                'max_tokens' => 1,
                'messages' => array(
                    array('role' => 'user', 'content' => 'Hi'),
                ),
            )),
            '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 Anthropic', '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) {
        return array(
            'success' => false,
            'message' => __('Anthropic does not support embeddings for this plugin.', 'kitsune-ai-platform'),
        );
    }

    public function generate_image($prompt, $params) {
        return array(
            'success' => false,
            'message' => __('Anthropic does not support image generation.', 'kitsune-ai-platform'),
        );
    }
}
