<?php

namespace App\AiAgents\Providers;

use App\AiAgents\Contracts\LlmProviderInterface;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;

class MistralProvider implements LlmProviderInterface
{
    public function __construct(
        protected string $apiKey,
        protected string $apiUrl,
        protected string $model
    ) {}

    public function chat(array $messages): array
    {
        try {
            $response = Http::timeout(30)
                ->withHeaders([
                    'Authorization' => "Bearer {$this->apiKey}",
                    'Content-Type' => 'application/json',
                ])
                ->post("{$this->apiUrl}/chat/completions", [
                    'model' => $this->model,
                    'messages' => $messages,
                    'temperature' => 0.7,
                    'max_tokens' => 1000,
                ]);

            if (! $response->successful()) {
                Log::error('Mistral API error', [
                    'status' => $response->status(),
                    'body' => $response->body(),
                ]);
                throw new \Exception('Mistral service temporarily unavailable');
            }

            return $response->json();
        } catch (\Exception $e) {
            Log::error('Mistral chat error', ['error' => $e->getMessage()]);

            throw $e;
        }
    }

    public function getProviderName(): string
    {
        return 'mistral';
    }

    public function getModel(): string
    {
        return $this->model;
    }
}
