<?php
/**
 * سودانا AI Engine — POST /api/engine/run.php
 * Run an agent by ID
 */
require_once __DIR__ . '/../../config.php';
require_once __DIR__ . '/../../engine/Kernel.php';
Kernel::handle(['auth' => false, 'public' => true]);
require_once __DIR__ . '/../../engine/Logger.php';
require_once '../../engine/QueueEngine.php';
require_once '../../engine/EventBus.php';
require_once '../../engine/SupportEngines.php';
require_once '../../engine/AIEngine.php';
require_once '../../engine/AIClient.php';
require_once '../../engine/DecisionEngine.php';
require_once '../../engine/PolicyEngine.php';
require_once '../../engine/ControlEngine.php';
require_once '../../engine/TaskEngine.php';
require_once '../../engine/GrowthBrain.php';
require_once __DIR__ . '/../../engine/SafetyEngine.php';

header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, OPTIONS');
header('Access-Control-Allow-Headers: Authorization, Content-Type');
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') { http_response_code(204); exit; }
if ($_SERVER['REQUEST_METHOD'] !== 'POST') { http_response_code(405); echo json_encode(['error'=>'method_not_allowed']); exit; }

$auth    = $_SERVER['HTTP_AUTHORIZATION'] ?? $_SERVER['HTTP_X_API_KEY'] ?? '';
$rawKey  = str_replace('Bearer ', '', $auth);
$keyData = AIEngine::validateKey($rawKey);
if (!$keyData) { http_response_code(401); echo json_encode(['error'=>'invalid_api_key']); exit; }

$body    = json_decode(file_get_contents('php://input'), true) ?? [];
$agentId = (int)($body['agent_id'] ?? 0);
$input   = mb_substr(trim($body['input'] ?? ''), 0, 1000);

if (!$agentId || !$input) { http_response_code(400); echo json_encode(['error'=>'agent_id and input required']); exit; }

// TASK 2 FIX: SafetyEngine input check before agent execution
$_run_safety = SafetyEngine::evaluateInput($input, ['endpoint' => 'engine/run.php']);
if ($_run_safety['action'] === SafetyEngine::BLOCK) {
    http_response_code(422);
    echo json_encode(['error' => 'content_blocked', 'trace_id' => Logger::traceId()]);
    exit;
}

$result = AIEngine::runAgent($agentId, (int)$keyData['user_id'], $input);
if (isset($result['error'])) http_response_code(400);
echo json_encode($result, JSON_UNESCAPED_UNICODE);
