<?php
/**
 * POST /api/tasks/estimate
 * Pre-execution estimation endpoint.
 *
 * Request body:
 *   { "prompt": "اعمل دراسة جدوى مع 10 صور وفيديو" }
 *
 * Response (can afford):
 *   { ok:true, action:"awaiting_confirmation", plan:{...}, cost:{...},
 *     token:"EST_...", expires_in_seconds:1800, wallet_after_confirm:X }
 *
 * Response (insufficient funds):
 *   HTTP 402
 *   { ok:false, error:"insufficient_funds", required_sdg:X, available_sdg:Y,
 *     suggestions:[...], plan:{...} }
 *
 * Response (rate limited):
 *   HTTP 429
 *   { error:"estimation_rate_limited" | "estimation_daily_cap_reached" }
 */
require_once __DIR__ . '/../../config.php';
require_once __DIR__ . '/../../engine/Kernel.php';

// Governance: auth required, AI rate bucket, 10/min estimation rate
$ctx  = Kernel::handle(['auth' => true, 'rate' => 'ai']);
$body = Kernel::require(['prompt']);

// ── Prompt validation & sanitization ────────────────────
$rawPrompt = $body['prompt'] ?? '';

// Size limit: 1000 chars max (prevents abuse of AIAnalyzer)
$prompt = mb_substr(trim($rawPrompt), 0, 1000);
if (!$prompt) Kernel::fail('empty_prompt', 'وصف الطلب مطلوب', 400);

// Minimum meaningful length
if (mb_strlen($prompt) < 10) {
    Kernel::fail('prompt_too_short', 'الوصف قصير جداً. أضف تفاصيل أكثر.', 400);
}

// Sanitize: strip control characters, normalize whitespace
$prompt = preg_replace('/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/u', '', $prompt);
$prompt = preg_replace('/\s+/', ' ', $prompt);

// Reject if prompt is > 80% numbers/symbols (likely injection or garbage)
$arabicLatinCount = preg_match_all('/[\p{Arabic}\p{L}]/u', $prompt);
$totalNonSpace    = preg_match_all('/\S/u', $prompt);
if ($totalNonSpace > 0 && ($arabicLatinCount / $totalNonSpace) < 0.2) {
    Kernel::fail('prompt_invalid', 'النص يجب أن يحتوي على كلمات مفهومة.', 400);
}

// Full estimation + budget check + reservation hold
Kernel::estimateAndHold($ctx['user'], $prompt);
