<?php
// logic/ai_processor.php

require_once 'config.php';

/**
 * Analyzes an image using the latest Gemini 3 model
 */
function analyzeImageWithGemini($imagePath) {
    // שימוש בשם המודל המדויק מהרשימה שלך
    $url = "https://generativelanguage.googleapis.com/v1beta/models/gemini-3-flash-preview:generateContent?key=" . GEMINI_API_KEY;

    if (!file_exists($imagePath)) {
        return ['status' => 'error', 'message' => 'File not found at: ' . $imagePath];
    }

    $imageData = base64_encode(file_get_contents($imagePath));

    $data = [
        "contents" => [
            ["parts" => [
                ["text" => "Analyze this image for a food-sharing app. Return ONLY a JSON object with: is_food (boolean), label (Hebrew), description (Hebrew), is_safe (boolean)."],
                ["inline_data" => ["mime_type" => "image/jpeg", "data" => $imageData]]
            ]]
        ]
    ];

    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); 
    
    $response = curl_exec($ch);
    $error = curl_error($ch);
    curl_close($ch);

    if ($error) {
        return ['status' => 'error', 'message' => 'Curl Error: ' . $error];
    }

    $decodedResponse = json_decode($response, true);
    
    // בדיקת שגיאה מגוגל
    if (isset($decodedResponse['error'])) {
        return ['status' => 'error', 'message' => 'Google Error: ' . $decodedResponse['error']['message']];
    }

    // חילוץ הנתונים
    if (isset($decodedResponse['candidates'][0]['content']['parts'][0]['text'])) {
        $aiResultRaw = $decodedResponse['candidates'][0]['content']['parts'][0]['text'];
        
        // שליפת ה-JSON מתוך הטקסט
        preg_match('/\{.*\}/s', $aiResultRaw, $matches);
        
        if (isset($matches[0])) {
            $finalData = json_decode($matches[0], true);
            if (json_last_error() === JSON_ERROR_NONE) {
                return array_merge(['status' => 'success'], $finalData);
            }
        }
        return ['status' => 'error', 'message' => 'AI returned text but no valid JSON.'];
    }

    return ['status' => 'error', 'message' => 'Unexpected response structure', 'raw' => $decodedResponse];
}