<?php

namespace App\Domains\AI\Providers;

use App\Domains\AI\Contracts\AiProvider;
use App\Domains\AI\DTOs\AiProviderResponse;
use App\Support\PlatformSettings;
use Illuminate\Http\Client\Factory as HttpFactory;
use RuntimeException;

class OpenAiCompatibleProvider implements AiProvider
{
    public function __construct(
        protected HttpFactory $http,
    ) {
    }

    public function key(): string
    {
        return 'openai';
    }

    public function generateText(string $featureKey, string $systemPrompt, array $context = [], ?string $modelOverride = null): AiProviderResponse
    {
        $config = config('ai.providers.openai');
        $apiKey = PlatformSettings::get('AI_OPENAI_API_KEY', $config['api_key'] ?? null);

        if (! $apiKey) {
            throw new RuntimeException('AI_OPENAI_API_KEY is not configured.');
        }

        $startedAt = microtime(true);
        $model = $modelOverride ?: (string) PlatformSettings::get('AI_OPENAI_MODEL', $config['model'] ?? 'gpt-4.1-mini');
        $baseUrl = (string) PlatformSettings::get('AI_OPENAI_BASE_URL', $config['base_url'] ?? 'https://api.openai.com/v1');
        $timeout = (int) PlatformSettings::get('AI_OPENAI_TIMEOUT', $config['timeout'] ?? 20);

        $response = $this->http
            ->baseUrl(rtrim($baseUrl, '/'))
            ->withToken($apiKey)
            ->timeout($timeout)
            ->acceptJson()
            ->post('/chat/completions', [
                'model' => $model,
                'messages' => [
                    ['role' => 'system', 'content' => $systemPrompt],
                    ['role' => 'user', 'content' => json_encode($context, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE)],
                ],
                'response_format' => ['type' => 'json_object'],
            ])
            ->throw()
            ->json();

        $content = $response['choices'][0]['message']['content'] ?? '{}';
        $decoded = json_decode($content, true);

        if (! is_array($decoded)) {
            throw new RuntimeException('AI provider returned an invalid JSON payload.');
        }

        $usage = $response['usage'] ?? [];

        return new AiProviderResponse(
            providerKey: $this->key(),
            modelKey: $model,
            output: $decoded,
            confidenceScore: isset($decoded['confidence']) ? (float) $decoded['confidence'] : null,
            warnings: $decoded['warnings'] ?? [],
            tokensInput: $usage['prompt_tokens'] ?? null,
            tokensOutput: $usage['completion_tokens'] ?? null,
            latencyMs: (int) round((microtime(true) - $startedAt) * 1000),
        );
    }
}
