<?php

namespace App\Services;

use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;

class LLMService
{
    public static function analyze(string $prompt, string $provider = 'openai')
    {
        try {
            return $provider === 'gemini'
                ? self::callGemini($prompt)
                : self::callOpenAI($prompt);
        } catch (\Exception $e) {
            Log::error("LLMService error ({$provider}): " . $e->getMessage());
            return ['choices' => [['message' => ['content' => '{"error":"AI request failed"}']]]];
        }
    }

    protected static function callOpenAI(string $prompt)
    {
        $response = Http::withToken(env('OPENAI_API_KEY'))
            ->post('https://api.openai.com/v1/chat/completions', [
                'model' => 'gpt-4o-mini',
                'messages' => [
                    ['role' => 'system', 'content' => 'You are an ATS resume scoring assistant.'],
                    ['role' => 'user', 'content' => $prompt],
                ],
                'temperature' => 0.4,
            ]);

        return $response->json();
    }

    protected static function callGemini(string $prompt)
    {
        $response = Http::withToken(env('GEMINI_API_KEY'))
            ->post(env('GEMINI_BASE_URL', 'https://generativelanguage.googleapis.com/v1beta/openai') . '/chat/completions', [
                'model' => 'gemini-2.0-flash',
                'messages' => [
                    ['role' => 'system', 'content' => 'You are an ATS resume scoring assistant.'],
                    ['role' => 'user', 'content' => $prompt],
                ],
                'temperature' => 0.4,
            ]);

        return $response->json();
    }
}
