<?php
header('Content-Type: application/json');
require_once __DIR__ . '/../ai/LocalAIApi.php';
require_once __DIR__ . '/../ai/CustomOpenAI.php';
@include_once __DIR__ . '/../ai/keys.php';

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['success' => false, 'error' => 'Method not allowed']);
    exit;
}

if (!isset($_FILES['image']) || $_FILES['image']['error'] !== UPLOAD_ERR_OK) {
    echo json_encode(['success' => false, 'error' => 'No image uploaded or upload error']);
    exit;
}

$imagePath = $_FILES['image']['tmp_name'];
$imageSize = filesize($imagePath);
$imageData = base64_encode(file_get_contents($imagePath));
$imageType = $_FILES['image']['type'];
$apiKey = defined('OPENAI_API_KEY') ? OPENAI_API_KEY : '';

$prompt = "Analyze this image. If it's a photo of a dish, identify what it is and create a possible recipe for it. If it's a photo of a written recipe, extract the information from it.
Provide the information in JSON format IN ENGLISH:
- name: Dish/recipe name
- category: One of the following values: 'Drinks', 'Breakfast', 'Dinner', 'Appetizers'
- ingredients: Array of objects, each containing:
    - name: Ingredient name
    - quantity: Numeric quantity (float)
    - unit: Unit of measurement (e.g., 'g', 'kg', 'ml', 'l', 'pcs', 'pack')
- guests: Default number of guests/portions (integer)

Important:
1. Quantities should be specified per 1 person if possible. If you are creating a recipe for a dish, default to 1 or 2 guests.
2. Return ONLY the JSON object.
3. If something cannot be determined, make the most accurate assumption or specify null.";

if (!empty($apiKey)) {
    $ai = new CustomOpenAI($apiKey);
    $response = $ai->analyze([
        'model' => 'gpt-4o',
        'prompt' => $prompt,
        'image_base64' => $imageData,
        'image_type' => $imageType
    ]);

    if (!$response['success']) {
        echo json_encode(['success' => false, 'error' => $response['error']]);
        exit;
    }

    $recipeData = CustomOpenAI::decodeJson($response);
    if (!$recipeData) {
        echo json_encode(['success' => false, 'error' => 'Failed to parse AI response as JSON.']);
        exit;
    }

    echo json_encode(['success' => true, 'data' => $recipeData, 'source' => 'CustomOpenAI']);
    exit;
}

// Fallback to LocalAIApi
file_put_contents(__DIR__ . '/scan_debug.log', date('Y-m-d H:i:s') . " Processing image: type=$imageType, size=$imageSize bytes" . PHP_EOL, FILE_APPEND);
file_put_contents(__DIR__ . '/scan_debug.log', date('Y-m-d H:i:s') . " Data URL prefix: " . substr("data:$imageType;base64,$imageData", 0, 50) . "..." . PHP_EOL, FILE_APPEND);

$prompt = "Analyze this image. If it's a photo of a dish, identify what it is and create a possible recipe for it. If it's a photo of a written recipe, extract the information from it.
Provide the information in JSON format IN ENGLISH:
- name: Dish/recipe name
- category: One of the following values: 'Drinks', 'Breakfast', 'Dinner', 'Appetizers'
- ingredients: Array of objects, each containing:
    - name: Ingredient name
    - quantity: Numeric quantity (float)
    - unit: Unit of measurement (e.g., 'g', 'kg', 'ml', 'l', 'pcs', 'pack')
- guests: Default number of guests/portions (integer)

Important:
1. Quantities should be specified per 1 person if possible. If you are creating a recipe for a dish, default to 1 or 2 guests.
2. Return ONLY the JSON object.
3. If something cannot be determined, make the most accurate assumption or specify null.";

try {
    $response = LocalAIApi::createResponse([
        'model' => 'gpt-4o',
        'input' => [
            [
                'role' => 'user',
                'content' => [
                    [
                        'type' => 'text',
                        'text' => $prompt
                    ],
                    [
                        'type' => 'image_url',
                        'image_url' => [
                            'url' => "data:$imageType;base64,$imageData",
                            'detail' => 'auto'
                        ]
                    ]
                ]
            ]
        ]
    ]);

    if (!$response['success']) {
        file_put_contents(__DIR__ . '/scan_debug.log', date('Y-m-d H:i:s') . ' AI Scan Error: ' . ($response['error'] ?? 'AI request failed') . PHP_EOL, FILE_APPEND);
        throw new Exception($response['error'] ?? 'AI request failed');
    }

    file_put_contents(__DIR__ . '/scan_debug.log', date('Y-m-d H:i:s') . ' AI Full Response: ' . json_encode($response) . PHP_EOL, FILE_APPEND);
    $text = LocalAIApi::extractText($response);
    file_put_contents(__DIR__ . '/scan_debug.log', date('Y-m-d H:i:s') . ' AI Scan Raw Text: ' . $text . PHP_EOL, FILE_APPEND);
    $recipeData = LocalAIApi::decodeJsonFromResponse($response);

    if (!$recipeData) {
        file_put_contents(__DIR__ . '/scan_debug.log', date('Y-m-d H:i:s') . ' AI Scan JSON Parse Error. Raw: ' . $text . PHP_EOL, FILE_APPEND);
        throw new Exception('Failed to parse AI response as JSON. Please try again with a clearer image.');
    }

    echo json_encode(['success' => true, 'data' => $recipeData]);

} catch (Exception $e) {
    echo json_encode(['success' => false, 'error' => $e->getMessage()]);
}
