<?php

namespace App\Http\Controllers;

use Illuminate\Support\Facades\File;
use App\Custom\SQLConnection;
use App\Custom\Misc;
use stdClass;
use Response;
use CURLFile;
use Session;
use Request;
use Route;
use DB;


class GeminiController extends Controller
{
    public static function gemminiAiEndpoint($system, $user, $assistant, $providerKey, $modelo){                

        $respuesta = self::generarContenidoGemini($providerKey, $system, $user, $assistant, $modelo);        

        try {
            $texto = $respuesta['candidates'][0]['content']['parts'][0]['text'] ?? null;
    
            if (!$texto) {
                return response()->json(['error' => 'Texto no encontrado en la respuesta.'], 400);
            }
    
            $limpio = trim(preg_replace('/```(?:json)?|```/', '', $texto));
            $json = json_decode($limpio, true);
    
            if (json_last_error() !== JSON_ERROR_NONE) {
                return response()->json([
                    'error' => 'Error al parsear JSON',
                    'detalle' => json_last_error_msg()
                ], 400);
            }
            
            return response()->json($json);
    
        } catch (\Throwable $e) {
            return response()->json([
                'error' => 'Error inesperado',
                'mensaje' => $e->getMessage()
            ], 500);
        }  
    }

    public static function generarContenidoGemini($providerKey, $systemMessage, $userPrompt, $assistant = null, $modelo){

        //$url = env('GEMINI_API_URL') . urlencode($providerKey);
        //$model = "gemini-1.5-flash-8b-latest";
        $url = "https://generativelanguage.googleapis.com/v1beta/models/{$modelo}:generateContent";

        $contents = [];

        // Mensaje del sistema
        if (!empty($systemMessage)) {
            $contents[] = [
                "role" => "user",
                "parts" => [
                    ["text" => $systemMessage]
                ]
            ];
        }

        // Mensaje anterior del asistente (si hay)
        if (!empty($assistant)) {
            $contents[] = [
                "role" => "assistant",
                "parts" => [
                    ["text" => $assistant]
                ]
            ];
        }

        // Prompt del usuario
        $contents[] = [
            "role" => "user",
            "parts" => [
                ["text" => $userPrompt]
            ]
        ];

        $data = [
            "contents" => $contents
        ];

        $payload = json_encode($data);

        //$ch = curl_init($url);
        $ch = curl_init("{$url}?key={$providerKey}");

        curl_setopt_array($ch, [
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_POST => true,
            CURLOPT_HTTPHEADER => [
                "Content-Type: application/json"
            ],
            CURLOPT_POSTFIELDS => $payload
        ]);

        $response = curl_exec($ch);
        $error = curl_error($ch);

        curl_close($ch);

        if ($error) {
            return "Error en la solicitud cURL: " . $error;
        }
        
        return json_decode($response, true);
    }

    public static function testModelGemini(){      
        
        $providerKey = "AIzaSyCfKyb-L9d4_aXO04ieJW9qsP88HEi4lJA";
        $model = "gemini-1.5-flash-8b-latest";
        $prompt = "Explain how AI works in a few words";

        $url = "https://generativelanguage.googleapis.com/v1beta/models/{$model}:generateContent";

        // Parámetros de la solicitud
        $data = [
            'contents' => [
                'parts' => [
                    ['text' => $prompt]
                ]
            ]
        ];

        // Configurar la solicitud cURL
        $ch = curl_init("{$url}?key={$providerKey}");
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
        curl_setopt($ch, CURLOPT_HTTPHEADER, [
            'Content-Type: application/json'
        ]);

        // Ejecutar la solicitud y obtener la respuesta
        $response = curl_exec($ch);
        curl_close($ch);

        // Decodificar la respuesta JSON
        $responseData = json_decode($response, true);

        // Extraer y mostrar el texto generado
        if (isset($responseData['candidates'][0]['content']['parts'][0]['text'])) {
            echo $responseData['candidates'][0]['content']['parts'][0]['text'];
        } else {
            echo "Error: No se pudo obtener la respuesta.";
            print_r($responseData); // Para depuración
        }
    }
}
