<?php

namespace App\Services\Ai;

use Illuminate\Support\Facades\Http;
use Src\Exceptions\MyException;

class GeminiService extends BaseService
{
    public function __construct()
    {
        $this->setup('gemini');
    }

    public function process(?string $prompt = null): array
    {
        $prompt = $prompt ?: self::$prompt;

        $url = self::$api.'/'.self::$modal.':generateContent';

        $response = Http::withHeaders([
            'Content-Type' => 'application/json',
        ])->timeout(seconds: 60 * self::$timeout)->post($url.'?key='.self::$key, [
            'contents' => [
                [
                    'parts' => [
                        ['text' => $prompt],
                    ],
                ],
            ],
        ]);

        $json = $response->json();
        if (isset($json['error'])) {
            throw new MyException($json['error']['message'] ?? 'Unknown error');
        }
        // Store token usages for logging
        $usage = $json['usageMetadata'];
        if (isset($usage['promptTokenCount'])) {
            $this->storeTokenUsage([
                'model' => self::$modal,
                'prompt_token_count' => $usage['promptTokenCount'] ?? 0,
                'completion_tokens' => $usage['candidatesTokenCount'] ?? 0,
                'total_token_count' => $usage['totalTokenCount'] ?? 0,
            ]);
        }

        // Defensive check for Gemini output format
        $text = data_get($json, 'candidates.0.content.parts.0.text');

        // Gemini often returns markdown-style JSON in a code block. Strip it out.
        $cleaned = trim($text);
        $cleaned = preg_replace('/^```json|^```|```$/m', '', $cleaned);

        // Decode JSON string safely
        $data = json_decode($cleaned, true);

        // Return as array, or empty array if something went wrong
        return is_array($data) ? $data : [];
    }

    public function getPrompt(): string
    {
        return self::$prompt;
    }
}
