<?php
/**
 * POST /api/ai/generate_video.php
 * Generate AI video with budget enforcement
 *
 * Body: { prompt: string, duration?: '5s'|'15s'|'30s'|'60s' }
 */
require_once __DIR__ . '/../../config.php';
require_once __DIR__ . '/../../engine/Kernel.php';

$ctx = Kernel::handle([
    'auth'   => true,
    'rate'   => 'ai',
    'budget' => ['type' => 'video', 'service' => $_POST['duration'] ?? '15s'],
]);

$body = Kernel::require(['prompt']);
$prompt   = mb_substr(trim($body['prompt']), 0, 500);
$duration = in_array($body['duration'] ?? '', ['5s','15s','30s','60s'], true)
          ? $body['duration'] : '15s';

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

$r = Kernel::meteredAI('video', $duration, function() use ($prompt, $duration) {
    // TODO: Real Veo-3 / Sora call
    return [
        'text' => '', 'content' => '',
        'video_url' => null, 'tokens_in' => 0, 'tokens_out' => 0,
        'cost_usd' => 1.50, 'provider' => 'veo',
        '_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,
    'video_url'    => $r['result']['video_url'] ?? null,
    'duration'     => $duration,
    'charged_sdg'  => $r['charged_sdg'],
    'wallet_after' => $r['wallet_after'],
]);
