<?php
declare(strict_types=1);

namespace Celena\Core\Ai\Provider;

use Celena\Core\Ai\ProviderInterface;
use RuntimeException;

/**
 * Провайдер Anthropic (Claude). API: https://docs.anthropic.com/
 * Использует curl, никаких внешних SDK.
 */
final class AnthropicProvider implements ProviderInterface
{
    public function __construct(
        private readonly string $apiKey,
        private readonly string $model = 'claude-sonnet-4-6',
    ) {
    }

    public function name(): string { return 'anthropic'; }

    public function complete(string $system, string $user, array $opts = []): string
    {
        $payload = [
            'model' => $opts['model'] ?? $this->model,
            'max_tokens' => (int) ($opts['max_tokens'] ?? 1024),
            'system' => $system,
            'messages' => [
                ['role' => 'user', 'content' => $user],
            ],
        ];
        if (isset($opts['temperature'])) {
            $payload['temperature'] = (float) $opts['temperature'];
        }

        $ch = curl_init('https://api.anthropic.com/v1/messages');
        curl_setopt_array($ch, [
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_POST => true,
            CURLOPT_HTTPHEADER => [
                'Content-Type: application/json',
                'x-api-key: ' . $this->apiKey,
                'anthropic-version: 2023-06-01',
            ],
            CURLOPT_POSTFIELDS => json_encode($payload, JSON_UNESCAPED_UNICODE),
            CURLOPT_TIMEOUT => 60,
        ]);
        $body = curl_exec($ch);
        $status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
        $err = curl_error($ch);
        curl_close($ch);

        if ($body === false) {
            throw new RuntimeException('Anthropic request failed: ' . $err);
        }
        $data = json_decode((string) $body, true);
        if ($status >= 400) {
            $msg = is_array($data) ? ($data['error']['message'] ?? (string) $body) : (string) $body;
            throw new RuntimeException('Anthropic error ' . $status . ': ' . $msg);
        }
        $text = '';
        foreach ((array) ($data['content'] ?? []) as $block) {
            if (is_array($block) && ($block['type'] ?? '') === 'text') {
                $text .= (string) $block['text'];
            }
        }
        return trim($text);
    }
}
