<?php

namespace App\AiAgents\Providers;

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

class DeepSeekProvider 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('DeepSeek API error', [
                    'status' => $response->status(),
                    'body' => $response->body(),
                ]);
                throw new \Exception('DeepSeek service temporarily unavailable');
            }

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

            throw $e;
        }
    }

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

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