<?php
/**
 * Anthropic Claude Provider
 */

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

class AIAutotool_AI_Provider_Anthropic extends AIAutotool_AI_Provider_Base {
    protected $name = 'Anthropic Claude';
    protected $id = 'anthropic';
    protected $base_url = 'https://api.anthropic.com/v1';
    protected $default_model = 'claude-sonnet-4-5';
    protected $available_models = array(
        'claude-sonnet-4-5' => 'Claude Sonnet 4.5',
        'claude-sonnet-4-5-20250929' => 'Claude Sonnet 4.5 (2025-09-29)',
        'claude-haiku-4-5-20251001' => 'Claude Haiku 4.5',
        'claude-sonnet-4-20250514' => 'Claude Sonnet 4',
        'claude-3-7-sonnet-20250219' => 'Claude 3.7 Sonnet',
    );

    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()) {
        if (!$this->is_configured()) {
            return array(
                'success' => false,
                'error' => 'Anthropic API key not configured'
            );
        }

        $options = $this->parse_options($options);
        $prepared = $this->prepare_messages($messages);
        $body = array(
            'model' => $options['model'],
            'messages' => $prepared['messages'],
            'max_tokens' => intval($options['max_tokens']),
            'temperature' => floatval($options['temperature']),
            'top_p' => floatval($options['top_p'])
        );

        if (!empty($prepared['system'])) {
            $body['system'] = $prepared['system'];
        }

        $response = $this->make_request(
            $this->base_url . '/messages',
            $body,
            'POST',
            array(
                'x-api-key' => $this->api_key,
                'anthropic-version' => '2023-06-01',
                'Content-Type' => 'application/json'
            )
        );

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

        $data = $response['data'];
        $content = '';
        if (isset($data['content']) && is_array($data['content'])) {
            foreach ($data['content'] as $block) {
                if (isset($block['text'])) {
                    $content .= $block['text'];
                }
            }
        }

        if ($content === '') {
            return array(
                'success' => false,
                'error' => 'Invalid response structure: missing content text'
            );
        }

        return array(
            'success' => true,
            'content' => $content,
            'usage' => isset($data['usage']) ? $data['usage'] : null,
            'model' => isset($data['model']) ? $data['model'] : $options['model'],
            'finish_reason' => isset($data['stop_reason']) ? $data['stop_reason'] : null
        );
    }

    public function test_connection() {
        if (!$this->is_configured()) {
            return array(
                'success' => false,
                'message' => 'Anthropic API key not configured'
            );
        }

        $result = $this->chat_completion(array(
            array('role' => 'user', 'content' => 'Reply with OK.')
        ), array(
            'model' => $this->default_model,
            'temperature' => 0.2,
            'max_tokens' => 32
        ));

        if ($result['success']) {
            return array(
                'success' => true,
                'message' => 'Anthropic 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' => 'Anthropic 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 prepare_messages($messages) {
        $system_parts = array();
        $anthropic_messages = array();

        foreach ($messages as $message) {
            $role = isset($message['role']) ? $message['role'] : 'user';
            $content = isset($message['content']) ? $message['content'] : '';

            if ($role === 'system') {
                $system_parts[] = is_string($content) ? $content : wp_json_encode($content);
                continue;
            }

            if (!in_array($role, array('user', 'assistant'), true)) {
                $role = 'user';
            }

            $anthropic_messages[] = array(
                'role' => $role,
                'content' => is_string($content) ? $content : wp_json_encode($content)
            );
        }

        if (empty($anthropic_messages)) {
            $anthropic_messages[] = array(
                'role' => 'user',
                'content' => 'Hello'
            );
        }

        return array(
            'system' => implode("\n\n", $system_parts),
            'messages' => $anthropic_messages
        );
    }
}
