<?php

namespace App\Services\AI;

use Illuminate\Support\Facades\Http;

class ClaudeProvider extends BaseAiProvider
{
    public function getIdentifier(): string
    {
        return 'claude';
    }

    public function generate(string $prompt, array $options = []): array
    {
        $key = $options['key'] ?? $this->config['key'] ?? null;
        if (! $key) {
            return ['success' => false, 'error' => 'API Key not configured.'];
        }

        $model = $options['model'] ?? $this->config['default_model'] ?? 'claude-3-5-sonnet-20240620';
        $instruction = $options['instruction'] ?? $this->config['instruction'] ?? '';

        $startTime = microtime(true);

        try {
            $res = Http::timeout(60)->withHeaders([
                'x-api-key' => $key,
                'anthropic-version' => '2023-06-01',
                'content-type' => 'application/json',
            ])->post('https://api.anthropic.com/v1/messages', [
                'model' => $model,
                'max_tokens' => (int) ($options['max_tokens'] ?? $this->config['max_tokens'] ?? 2000),
                'system' => $instruction,
                'messages' => [
                    ['role' => 'user', 'content' => $prompt],
                ],
                'temperature' => (float) ($options['temperature'] ?? $this->config['temperature'] ?? 0.7),
            ]);

            if ($res->failed()) {
                $error = $res->json()['error']['message'] ?? 'Claude Error';
                $this->logUsage([
                    'model' => $model,
                    'prompt' => $prompt,
                    'status' => 'failed',
                    'error' => $error,
                ]);

                return ['success' => false, 'error' => $error];
            }

            $data = $res->json();
            $response = $data['content'][0]['text'];
            $usage = [
                'prompt_tokens' => $data['usage']['input_tokens'] ?? 0,
                'completion_tokens' => $data['usage']['output_tokens'] ?? 0,
                'total_tokens' => ($data['usage']['input_tokens'] ?? 0) + ($data['usage']['output_tokens'] ?? 0),
            ];

            $result = [
                'success' => true,
                'response' => $response,
                'usage' => $usage,
                'model' => $model,
                'latency' => microtime(true) - $startTime,
            ];

            $this->logUsage([
                'model' => $model,
                'prompt' => $prompt,
                'response' => $response,
                'usage' => $usage,
                'status' => 'success',
                'metadata' => ['latency' => $result['latency']],
            ]);

            return $result;

        } catch (\Exception $e) {
            return ['success' => false, 'error' => $e->getMessage()];
        }
    }
}
