<?php

namespace App\Services;

use Illuminate\Support\Facades\Http;

class AiClientService
{
    public function callJson(string $prompt): array
    {
        $driver = config('ai.driver', 'deepseek');

        return match ($driver) {
            'deepseek' => $this->callDeepSeek($prompt),
            'openai' => $this->callOpenAi($prompt),
            default => throw new \RuntimeException("Unsupported AI driver: {$driver}"),
        };
    }

    private function callDeepSeek(string $prompt): array
    {
        $config = config('ai.deepseek', []);
        $apiKey = $config['api_key'] ?? env('DEEPSEEK_API_KEY');
        $baseUrl = rtrim($config['base_url'] ?? 'https://api.deepseek.com/v1', '/');
        $model = $config['model'] ?? 'deepseek-chat';
        $timeout = (int) ($config['timeout'] ?? 30);

        $response = Http::withHeaders([
            'Authorization' => "Bearer {$apiKey}",
            'Content-Type' => 'application/json',
        ])->timeout($timeout)->post($baseUrl . '/chat/completions', [
            'model' => $model,
            'messages' => [
                ['role' => 'user', 'content' => $prompt],
            ],
            'temperature' => 0.1,
        ]);

        if (!$response->successful()) {
            throw new \RuntimeException('DeepSeek API error: ' . $response->body());
        }

        $content = $response->json('choices.0.message.content');
        return $this->parseJsonResponse($content);
    }

    private function callOpenAi(string $prompt): array
    {
        $config = config('ai.openai', []);
        $apiKey = $config['api_key'] ?? env('OPENAI_API_KEY');
        $baseUrl = rtrim($config['base_url'] ?? 'https://api.openai.com/v1', '/');
        $model = $config['model'] ?? 'gpt-3.5-turbo';
        $timeout = (int) ($config['timeout'] ?? 30);

        $response = Http::withHeaders([
            'Authorization' => "Bearer {$apiKey}",
            'Content-Type' => 'application/json',
        ])->timeout($timeout)->post($baseUrl . '/chat/completions', [
            'model' => $model,
            'messages' => [
                ['role' => 'user', 'content' => $prompt],
            ],
            'temperature' => 0.1,
        ]);

        if (!$response->successful()) {
            throw new \RuntimeException('OpenAI API error: ' . $response->body());
        }

        $content = $response->json('choices.0.message.content');
        return $this->parseJsonResponse($content);
    }

    private function parseJsonResponse(?string $content): array
    {
        if (!$content) {
            return [];
        }

        $content = trim($content);
        $content = preg_replace('/```(?:json)?/i', '', $content);
        $content = str_replace('```', '', $content);
        $content = trim($content);

        $data = json_decode($content, true);
        if (json_last_error() !== JSON_ERROR_NONE) {
            $start = strpos($content, '{');
            $end = strrpos($content, '}');
            if ($start !== false && $end !== false && $end > $start) {
                $slice = substr($content, $start, $end - $start + 1);
                $data = json_decode($slice, true);
            }
        }

        return is_array($data) ? $data : [];
    }
}
