<?php
/**
 * سودانا — AIOrchestrator v2
 * Single pipeline. Called ONLY by Worker. Never from web requests.
 */
// FinancialAgent available via Worker require chain
class AIOrchestrator {

    public static function run(string $event, array $payload): void {
        $start = round(microtime(true) * 1000);
        $actions  = DecisionEngine::handle($event, $payload);
        $approved = PolicyEngine::evaluate($actions, $payload);
        $final    = array_values(array_filter($approved, fn($a) => ControlEngine::approve($a, $payload)));
        TaskEngine::dispatch($final);
        GrowthBrain::observe($event, $payload);
        ReinforcementEngine::update($event);
        self::logDecision($event, $final);
        Monitoring::log('orchestrator.latency_ms', round(microtime(true)*1000) - $start, ['event'=>$event]);
        Monitoring::log('orchestrator.actions', count($final), ['event'=>$event]);
    }

    private static function logDecision(string $event, array $actions): void {
        try {
            db()->prepare("INSERT INTO ai_decisions (event, decision, score, created_at) VALUES (?,?,?,NOW())")
                ->execute([$event, json_encode($actions, JSON_UNESCAPED_UNICODE), count($actions)]);
        } catch (Throwable $e) { error_log("[AIOrchestrator] " . $e->getMessage()); }
    }
}
