<?php

declare(strict_types=1);

namespace ImovelZapAi\AiGateway\Infrastructure\Console;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\Http;
use Throwable;

final class PingOpenAiCommand extends Command
{
    protected $signature = 'ai:ping';

    protected $description = 'Testa se a API OpenAI está configurada e respondendo';

    public function handle(): int
    {
        $key = (string) (config('ai_gateway.providers.openai.api_key') ?: '');
        $base = rtrim((string) config('ai_gateway.providers.openai.base_url', 'https://api.openai.com/v1'), '/');
        $model = (string) config('ai_gateway.providers.openai.default_model', 'gpt-4.1-nano');

        $this->line('=== Teste OpenAI ===');
        $this->line("Base:  {$base}");
        $this->line("Model: {$model}");
        $this->line('Key:   '.(strlen($key) > 8
            ? substr($key, 0, 7).'…'.substr($key, -4).' ('.strlen($key).' chars)'
            : '(vazia)'));
        $this->newLine();

        if ($key === '') {
            $this->error('RESULTADO: FALHA — OPENAI_API_KEY vazia no .env');

            return self::FAILURE;
        }

        try {
            $response = Http::baseUrl($base)
                ->withToken($key)
                ->timeout(30)
                ->acceptJson()
                ->post('/chat/completions', [
                    'model' => $model,
                    'messages' => [
                        ['role' => 'user', 'content' => 'Responda apenas com a palavra OK.'],
                    ],
                    'max_tokens' => 16,
                    'temperature' => 0,
                ]);

            $this->line('HTTP: '.$response->status());

            if (! $response->successful()) {
                $this->error('RESULTADO: FALHA');
                $this->line($response->body());

                return self::FAILURE;
            }

            $body = $response->json();
            $text = trim((string) ($body['choices'][0]['message']['content'] ?? ''));
            $this->info("Resposta: {$text}");
            $this->line('Modelo: '.(string) ($body['model'] ?? $model));
            $this->line('Tokens: '.(int) ($body['usage']['total_tokens'] ?? 0));
            $this->info('RESULTADO: OK — API OpenAI respondendo');

            return self::SUCCESS;
        } catch (Throwable $e) {
            $this->error('RESULTADO: FALHA — '.$e->getMessage());

            return self::FAILURE;
        }
    }
}
