<?php

namespace App\Services\AI;

use Illuminate\Support\Facades\Http;

class GeminiProvider extends BaseAiProvider
{
    public function getIdentifier(): string
    {
        return 'gemini';
    }

    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'] ?? 'gemini-1.5-flash';
        $instruction = $options['instruction'] ?? $this->config['instruction'] ?? '';

        $startTime = microtime(true);

        try {
            $res = Http::timeout(60)->post("https://generativelanguage.googleapis.com/v1beta/models/{$model}:generateContent?key={$key}", [
                'contents' => [
                    ['parts' => [['text' => $instruction."\n\n".$prompt]]],
                ],
                'generationConfig' => [
                    'temperature' => (float) ($options['temperature'] ?? $this->config['temperature'] ?? 0.7),
                    'maxOutputTokens' => (int) ($options['max_tokens'] ?? $this->config['max_tokens'] ?? 2000),
                ],
            ]);

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

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

            $data = $res->json();
            $response = $data['candidates'][0]['content']['parts'][0]['text'] ?? 'No response';

            // Gemini doesn't always return token count in the same way, simplified for now
            $usage = [
                'prompt_tokens' => 0,
                'completion_tokens' => 0,
                'total_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()];
        }
    }
}
