<?php
/**
 * POST /api/flow/execute.php
 * Universal flow execution via FlowEngine
 * Connects: InferenceEngine → FlowEngine → BillingEngine → Execution
 */
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 __DIR__ . '/../../engine/InferenceEngine.php';
require_once __DIR__ . '/../../engine/FlowEngine.php';
require_once __DIR__ . '/../../engine/BillingEngine.php';
require_once __DIR__ . '/../../engine/AssistantEngine.php';

// session_start() removed — Kernel::handle manages sessions
if ($_SERVER['REQUEST_METHOD'] !== 'POST') { http_response_code(405); die(json_encode(['error'=>'method_not_allowed'])); }

$data   = json_decode(file_get_contents('php://input'), true) ?: [];
$userId = (int)($_SESSION['user_id'] ?? 0);
$query  = trim($data['query'] ?? '');
$sector = trim($data['sector'] ?? '');

if (!$query) { http_response_code(422); die(json_encode(['error'=>'query required'])); }

$traceId = uniqid('flow_exec_', true);

try {
    // 1. Inference (if sector not provided)
    if (!$sector) {
        $ie = InferenceEngine::infer($query, ['user_id'=>$userId]);
        $sector = $ie['sector'] ?? 'general';
    } else {
        $ie = ['sector'=>$sector,'execution_mode'=>'provider_booking','billing_class'=>'premium','requires_provider'=>true,'tools'=>['ai_chat','provider_match']];
    }

    // 2. Run FlowEngine
    $result = FlowEngine::run($sector, $query, $userId, array_merge($data, ['trace_id'=>$traceId,'execution_id'=>$traceId]));

    echo json_encode(array_merge($result, [
        'trace_id' => $traceId,
        'sector'   => $sector,
        'query'    => $query,
    ]), JSON_UNESCAPED_UNICODE);

} catch (Throwable $e) {
    error_log("[flow/execute] " . $e->getMessage());
    // NO dead end — fallback to AI answer
    http_response_code(200);
    echo json_encode([
        'status'    => 'fallback_answer',
        'action'    => 'ai_answer',
        'message'   => 'يتم معالجة طلبك...',
        'sector'    => $sector,
        'trace_id'  => $traceId,
        'error_log' => $e->getMessage(),
    ], JSON_UNESCAPED_UNICODE);
}
