<?php
/**
 * POST /api/ai/answer
 * Unified AI answer endpoint — routes through full pipeline
 * BankAnswerEngine + InferenceEngine + Gateway
 * Secure: session required
 */
require_once __DIR__ . '/../../config.php';
require_once __DIR__ . '/../../engine/Kernel.php';
require_once __DIR__ . '/../../engine/Logger.php';   // BRIDGE: unified trace_id
require_once __DIR__ . '/../../engine/Gateway.php';
require_once __DIR__ . '/../../engine/BankAnswerEngine.php';
require_once __DIR__ . '/../../engine/InferenceEngine.php';

// KERNEL: trace + optional auth
$_k = Kernel::handle(['auth' => 'optional']);

// Logger trace established BEFORE any engine call — same ID flows to ai_usage
if (session_status() === PHP_SESSION_NONE) {
    if (function_exists('start_secure_session')) start_secure_session();
    else session_start();
}

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) ?: [];
$question = trim($data['question'] ?? $data['q'] ?? '');
$lang     = in_array($data['lang'] ?? '', ['ar', 'en']) ? $data['lang'] : 'auto';
// $traceId already set above via Logger::traceId()

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

$userId = (int)($_SESSION['user_id'] ?? 0);
$t0     = microtime(true);

// Step 1: Check IE for bank_qa sector
$ie = InferenceEngine::infer($question);
if ($ie && isset($ie['r']) && str_starts_with($ie['r'] ?? '', 'bank_qa:')) {
    $bqa = BankAnswerEngine::answer($question, $lang);
    echo json_encode([
        'answer'     => $bqa['answer'],
        'source'     => 'bank_qa',
        'category'   => $bqa['category'],
        'confidence' => $bqa['confidence'],
        'trace_id'   => $bqa['trace_id'],
        'latency_ms' => round((microtime(true) - $t0) * 1000),
        'lang'       => $bqa['lang'],
    ], JSON_UNESCAPED_UNICODE);
    exit;
}

// Step 2: Route through Gateway for full pipeline
$user = $userId ? ['id' => $userId] : null;
$response = Gateway::handle([
    'question' => $question,
    'user'     => $user,
    'ip'       => $_SERVER['REMOTE_ADDR'] ?? '0.0.0.0',
    'lang'     => $lang,
    'trace_id' => $traceId,  // BRIDGE: unified trace → ai_usage
]);

echo json_encode(array_merge($response, [
    'trace_id'   => $traceId,
    'latency_ms' => round((microtime(true) - $t0) * 1000),
]), JSON_UNESCAPED_UNICODE);
