<?php

namespace GriffinForms\Includes\Ai\Transports;

use GriffinForms\Includes\Ai\Contracts\AiClientInterface;
use GriffinForms\Includes\Ai\Exceptions\AiBrokerError;
use GriffinForms\Includes\Ai\Exceptions\ButlerTimeoutException;

class AnthropicRestTransport implements AiClientInterface
{
    private const ENDPOINT = 'https://api.anthropic.com/v1/messages';
    private const API_VERSION = '2023-06-01';

    protected $api_key;
    protected $model;
    protected $timeout;
    protected $max_tokens;

    public function __construct(string $api_key, string $model, int $timeout = 20, ?int $max_tokens = null)
    {
        $this->api_key    = $api_key;
        $this->model      = $model ?: 'claude-haiku-4-5';
        $this->timeout    = $timeout > 0 ? $timeout : 20;
        $this->max_tokens = ($max_tokens !== null && $max_tokens > 0) ? $max_tokens : 4096;
    }

    public function request(string $prompt, array $context = []): array
    {
        if (empty($this->api_key)) {
            throw new AiBrokerError('AI request aborted: Missing API key.', 401);
        }

        $system_context = $context['system'] ?? 'You are a helpful assistant.';

        $body = [
            'model'      => $this->model,
            'max_tokens' => $this->max_tokens,
            'system'     => $system_context,
            'messages'   => [
                ['role' => 'user', 'content' => $prompt],
            ],
        ];

        $args = [
            'headers' => [
                'x-api-key'         => $this->api_key,
                'anthropic-version' => self::API_VERSION,
                'Content-Type'      => 'application/json',
            ],
            'body'    => wp_json_encode($body),
            'timeout' => $this->timeout,
        ];

        if (defined('WP_DEBUG') && WP_DEBUG) {
            error_log('[GriffinForms AI →] model=' . $this->model . ' system=' . $system_context . ' prompt=' . $prompt);
        }

        $response = wp_remote_post(self::ENDPOINT, $args);

        if (is_wp_error($response)) {
            if ($this->isTimeoutError($response)) {
                throw new ButlerTimeoutException('The AI provider timed out before returning a response.', 408);
            }
            throw new AiBrokerError('Network failure: ' . $response->get_error_message(), 500);
        }

        $code          = wp_remote_retrieve_response_code($response);
        $response_body = wp_remote_retrieve_body($response);

        if (defined('WP_DEBUG') && WP_DEBUG) {
            error_log('[GriffinForms AI ←] HTTP=' . $code . ' body=' . $response_body);
        }

        if ($code !== 200) {
            throw new AiBrokerError('API integration error: HTTP ' . $code . ' (' . $response_body . ')', $code);
        }

        $decoded = json_decode($response_body, true);

        if (json_last_error() !== JSON_ERROR_NONE) {
            throw new AiBrokerError('Invalid JSON response retrieved from AI service provider.', 500);
        }

        return [
            'success' => true,
            'content' => $decoded['content'][0]['text'] ?? '',
            'raw'     => $decoded,
        ];
    }

    protected function isTimeoutError(\WP_Error $response): bool
    {
        $message = strtolower((string) $response->get_error_message());
        $code    = (string) $response->get_error_code();

        return str_contains($message, 'timed out')
            || str_contains($message, 'timeout')
            || str_contains($message, 'curl error 28')
            || $code === 'http_request_timeout';
    }
}
