<?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;
}

$prompt = $_POST['prompt'] ?? "Analyze this image and describe what you see.";
$model = $_POST['model'] ?? 'gpt-4o';
$imageUrl = $_POST['image_url'] ?? null;
$apiKey = defined('OPENAI_API_KEY') ? OPENAI_API_KEY : '';

// Prefer CustomOpenAI if key is available
$useCustom = !empty($apiKey);

if ($useCustom) {
    $ai = new CustomOpenAI($apiKey);
    $params = [
        'model' => $model,
        'prompt' => $prompt
    ];

    if (isset($_FILES['image']) && $_FILES['image']['error'] === UPLOAD_ERR_OK) {
        $params['image_base64'] = base64_encode(file_get_contents($_FILES['image']['tmp_name']));
        $params['image_type'] = $_FILES['image']['type'];
    } elseif (!empty($imageUrl)) {
        $params['image_url'] = $imageUrl;
    }

    $response = $ai->analyze($params);

    if ($response['success']) {
        echo json_encode([
            'success' => true,
            'text' => CustomOpenAI::extractText($response),
            'data' => CustomOpenAI::decodeJson($response),
            'source' => 'CustomOpenAI'
        ]);
    } else {
        echo json_encode(['success' => false, 'error' => $response['error']]);
    }
    exit;
}

// Fallback to LocalAIApi (original logic)
$content = [['type' => 'text', 'text' => $prompt]];

// Handle file upload
if (isset($_FILES['image']) && $_FILES['image']['error'] === UPLOAD_ERR_OK) {
    $imagePath = $_FILES['image']['tmp_name'];
    $imageData = base64_encode(file_get_contents($imagePath));
    $imageType = $_FILES['image']['type'];
    $content[] = [
        'type' => 'image_url',
        'image_url' => [
            'url' => "data:$imageType;base64,$imageData",
            'detail' => 'auto'
        ]
    ];
} elseif (!empty($imageUrl)) {
    // Handle image URL
    $content[] = [
        'type' => 'image_url',
        'image_url' => [
            'url' => $imageUrl,
            'detail' => 'auto'
        ]
    ];
} else {
    // If no image, it's just a text prompt (optional but allowed)
}

try {
    $response = LocalAIApi::createResponse([
        'model' => $model,
        'input' => [
            [
                'role' => 'user',
                'content' => $content
            ]
        ]
    ]);

    if (!$response['success']) {
        throw new Exception($response['error'] ?? 'AI request failed');
    }

    $text = LocalAIApi::extractText($response);
    $json = LocalAIApi::decodeJsonFromResponse($response);

    echo json_encode([
        'success' => true,
        'text' => $text,
        'data' => $json,
        'raw' => $response
    ]);

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