<?php
/**
 * POST /api/ai/generate_image.php
 * Generate AI image with budget enforcement
 *
 * Body: { prompt: string, size?: '512x512'|'1024x1024'|'1024x1792' }
 *
 * This is the FIRST endpoint built using the Kernel pattern.
 * Notice: 7 lines of business logic, everything else handled by gates.
 */
require_once __DIR__ . '/../../config.php';
require_once __DIR__ . '/../../engine/Kernel.php';

// Single-line governance: auth + rate + budget pre-check
$ctx = Kernel::handle([
    'auth'   => true,
    'rate'   => 'ai',
    'budget' => ['type' => 'image', 'service' => $_POST['size'] ?? '1024x1024'],
]);

$body = Kernel::require(['prompt']);
$prompt = mb_substr(trim($body['prompt']), 0, 500);
$size   = in_array($body['size'] ?? '', ['512x512','1024x1024','1024x1792'], true)
        ? $body['size'] : '1024x1024';

if (!$prompt) Kernel::fail('empty_prompt', 'الوصف مطلوب', 400);

// Metered AI execution (budget already pre-checked, this debits)
$r = Kernel::meteredAI('image', $size, function() use ($prompt, $size) {
    // TODO: Real Gemini/DALL-E image generation call
    // For now, return a placeholder structure indicating "not implemented"
    return [
        'text'       => '',
        'content'    => '',
        'image_url'  => null,
        'tokens_in'  => 0,
        'tokens_out' => 0,
        'cost_usd'   => 0.04,  // typical cost
        'provider'   => 'gemini',
        '_placeholder' => true,
    ];
});

if (!empty($r['result']['_placeholder'])) {
    Kernel::respond([
        'ok' => false,
        'message' => 'توليد الصور — قيد التطوير. السعر تم احتسابه.',
        'charged_sdg' => $r['charged_sdg'],
        'wallet_after' => $r['wallet_after'],
    ], 501);
}

Kernel::respond([
    'ok'           => true,
    'image_url'    => $r['result']['image_url'] ?? null,
    'size'         => $size,
    'prompt'       => $prompt,
    'charged_sdg'  => $r['charged_sdg'],
    'wallet_after' => $r['wallet_after'],
    'cost_usd'     => $r['cost_usd'],
]);
