Files
wevads-platform/scripts/opt__wevads-arsenal__public__api__api-gateway-light.php
2026-02-26 04:53:11 +01:00

303 lines
9.7 KiB
PHP
Executable File

<?php
/**
* 🚪 API GATEWAY LIGHT - Version simplifiée sans base de données
* Version: 1.0 - Février 2026
*/
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization');
class ApiGatewayLight {
private $modules = [
'mind' => 'Weval Mind Core',
'hamid' => 'HAMID IA Engine',
'brain' => 'Brain Engine',
'status' => 'System Status',
'health' => 'Health Check'
];
/**
* Get client IP
*/
private function getClientIp() {
$ip = $_SERVER['HTTP_X_FORWARDED_FOR'] ??
$_SERVER['HTTP_CLIENT_IP'] ??
$_SERVER['REMOTE_ADDR'] ??
'0.0.0.0';
return $ip;
}
/**
* Log message
*/
private function logMessage($level, $module, $message, $data = null) {
$timestamp = date('Y-m-d H:i:s');
$logEntry = "[$timestamp] [$level] [$module] $message";
if ($data) {
$logEntry .= " | Data: " . json_encode($data);
}
// Log to file
$logFile = '/var/log/wevads/api-gateway-' . date('Y-m-d') . '.log';
@file_put_contents($logFile, $logEntry . PHP_EOL, FILE_APPEND);
return true;
}
/**
* Route request
*/
private function routeRequest($module, $action, $data) {
switch ($module) {
case 'status':
return $this->getSystemStatus();
case 'health':
return $this->healthCheck();
case 'mind':
return $this->routeToMind($action, $data);
case 'hamid':
return $this->routeToHamid($action, $data);
default:
return [
'error' => 'Module not found',
'available_modules' => array_keys($this->modules)
];
}
}
/**
* Get system status
*/
private function getSystemStatus() {
// Check services
$services = [
'apache' => $this->checkService('apache2'),
'postgresql' => $this->checkService('postgresql')
];
// Get system metrics
$load = @sys_getloadavg();
$memory = @shell_exec("free -m | awk 'NR==2 {printf \"%.1f\", $3/$2*100}' 2>/dev/null");
$disk = @shell_exec("df / | awk 'NR==2 {print $5}' | sed 's/%//' 2>/dev/null");
return [
'status' => 'operational',
'timestamp' => date('Y-m-d H:i:s'),
'services' => $services,
'metrics' => [
'cpu_load' => [
'1min' => $load[0] ?? 0,
'5min' => $load[1] ?? 0,
'15min' => $load[2] ?? 0
],
'memory_usage' => floatval($memory) ?: 0,
'disk_usage' => floatval($disk) ?: 0
],
'modules' => $this->modules,
'gateway' => 'light_version'
];
}
/**
* Health check
*/
private function healthCheck() {
$checks = [];
// Check services
$services = ['apache2', 'postgresql'];
foreach ($services as $service) {
$checks['service_' . $service] = [
'status' => $this->checkService($service) ? 'running' : 'stopped'
];
}
// Check disk space
$disk = @shell_exec("df / | awk 'NR==2 {print $5}' | sed 's/%//' 2>/dev/null");
$checks['disk_space'] = [
'usage_percent' => floatval($disk) ?: 0,
'status' => (floatval($disk) > 85) ? 'warning' : 'healthy'
];
// Determine overall status
$overall = 'healthy';
foreach ($checks as $check) {
if (isset($check['status']) && $check['status'] === 'stopped') {
$overall = 'unhealthy';
break;
}
}
return [
'status' => $overall,
'checks' => $checks,
'timestamp' => date('Y-m-d H:i:s'),
'uptime' => @shell_exec("uptime -p 2>/dev/null") ?: 'unknown'
];
}
/**
* Route to Weval Mind
*/
private function routeToMind($action, $data) {
$validActions = ['autonomous_cycle', 'status', 'report'];
if (!in_array($action, $validActions)) {
return [
'error' => 'Invalid action for mind module',
'valid_actions' => $validActions
];
}
if ($action === 'autonomous_cycle') {
// Call the simple API
$url = "http://localhost:5890/api/weval-mind-core-simple.php?action=autonomous_cycle";
$response = @file_get_contents($url);
if ($response === false) {
return ['error' => 'Failed to call mind API'];
}
$result = json_decode($response, true);
return $result ?: ['error' => 'Invalid response from mind API'];
}
return [
'module' => 'mind',
'action' => $action,
'status' => 'available',
'message' => 'Mind module operational'
];
}
/**
* Route to HAMID IA
*/
private function routeToHamid($action, $data) {
$validActions = ['chat', 'providers', 'stats'];
if (!in_array($action, $validActions)) {
return [
'error' => 'Invalid action for hamid module',
'valid_actions' => $validActions
];
}
if ($action === 'chat') {
if (empty($data['message'])) {
return ['error' => 'Message is required for chat action'];
}
return [
'response' => "🤖 **HAMID IA Light**\n\nJe reçois votre message : \"" .
htmlspecialchars(substr($data['message'], 0, 200)) . "\"\n\n" .
"**Capacités disponibles:**\n" .
"• Analyse technique de l'architecture\n" .
"• Diagnostic des problèmes système\n" .
"• Réponses basées sur la connaissance système\n\n" .
"**Version complète en développement**",
'provider' => 'gateway_light',
'timestamp' => date('Y-m-d H:i:s')
];
}
if ($action === 'providers') {
return [
'providers' => [
['name' => 'Cerebras', 'status' => 'available', 'priority' => 1],
['name' => 'Groq', 'status' => 'available', 'priority' => 2],
['name' => 'DeepSeek', 'status' => 'available', 'priority' => 3],
['name' => 'Gemini', 'status' => 'available', 'priority' => 4],
['name' => 'Claude', 'status' => 'available', 'priority' => 5]
],
'note' => 'Light version - Providers configuration en attente'
];
}
return [
'module' => 'hamid',
'action' => $action,
'status' => 'available',
'message' => 'HAMID module operational'
];
}
/**
* Check if service is running
*/
private function checkService($service) {
$status = @shell_exec("systemctl is-active $service 2>/dev/null");
return trim($status) === 'active';
}
/**
* Process incoming request
*/
public function processRequest() {
try {
// Get request data
$method = $_SERVER['REQUEST_METHOD'];
$clientIp = $this->getClientIp();
// Handle preflight requests
if ($method === 'OPTIONS') {
http_response_code(200);
exit;
}
// Get module and action
$module = $_GET['module'] ?? $_POST['module'] ?? 'status';
$action = $_GET['action'] ?? $_POST['action'] ?? 'status';
// Get request data
$input = file_get_contents('php://input');
$data = json_decode($input, true);
if (json_last_error() !== JSON_ERROR_NONE) {
$data = $_POST ?: [];
}
// Log the request
$this->logMessage('INFO', 'API Gateway Light', 'Request received', [
'module' => $module,
'action' => $action,
'ip' => $clientIp,
'method' => $method
]);
// Route the request
$result = $this->routeRequest($module, $action, $data);
// Add metadata
$result['gateway'] = [
'version' => '1.0-light',
'timestamp' => date('Y-m-d H:i:s'),
'request_id' => 'REQ-' . uniqid()
];
// Return response
http_response_code(200);
echo json_encode($result, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
} catch (Exception $e) {
$this->logMessage('ERROR', 'API Gateway Light', 'Processing error: ' . $e->getMessage());
http_response_code(500);
echo json_encode([
'error' => 'Internal server error',
'message' => $e->getMessage(),
'timestamp' => date('Y-m-d H:i:s'),
'gateway' => 'light_version'
]);
}
}
}
// Handle request
$gateway = new ApiGatewayLight();
$gateway->processRequest();
?>