<?php
/**
 * Simple WebSocket Test - Writes to file instead of stdout
 */

// CRITICAL: Set CLI mode BEFORE anything else
// Force CLI mode detection
if (!defined('STDIN')) {
    define('STDIN', fopen('php://stdin', 'r'));
}

// Suppress ALL output BEFORE any includes
ini_set('display_errors', '0');
ini_set('log_errors', '1');
ini_set('output_buffering', '0');
ini_set('session.auto_start', '0');

// Prevent session from starting
if (function_exists('session_status') && session_status() === PHP_SESSION_NONE) {
    // Don't start session in CLI
}

while (ob_get_level() > 0) {
    ob_end_clean();
}

$baseDir = dirname(__DIR__);
$testLogFile = $baseDir . '/test-websocket.log';

// Clear previous test log
if (file_exists($testLogFile)) {
    unlink($testLogFile);
}

function testLog($message) {
    global $testLogFile;
    $timestamp = date('Y-m-d H:i:s');
    file_put_contents($testLogFile, "[$timestamp] $message\n", FILE_APPEND);
    error_log($message);
}

testLog("=== Testing WebSocket Client ===");
testLog("PHP SAPI: " . php_sapi_name());
testLog("Is CLI: " . (php_sapi_name() === 'cli' ? 'YES' : 'NO'));

try {
    // Temporarily override session functions to prevent headers
    if (!function_exists('session_start_override')) {
        function session_start_override($options = []) {
            if (php_sapi_name() === 'cli') {
                return false; // Don't start session in CLI
            }
            return session_start($options);
        }
    }
    
    require_once $baseDir . '/includes/config.php';
    testLog("✓ Config loaded");
    
    require_once $baseDir . '/includes/binance-api.php';
    require_once $baseDir . '/includes/binance-settings.php';
    require_once $baseDir . '/includes/websocket-client.php';
    testLog("✓ All includes loaded");
    
    // Check if Ratchet/Pawl is available
    if (!class_exists('Ratchet\Client\Connector')) {
        throw new Exception("Ratchet/Pawl not found. Run: composer require ratchet/pawl");
    }
    testLog("✓ Ratchet/Pawl library found");
    
    $settings = new BinanceP2PSettings($pdo);
    $apiKey = $settings->getBinanceApiKey();
    $secretKey = $settings->getBinanceSecretKey();
    
    if (empty($apiKey) || empty($secretKey)) {
        throw new Exception("Binance API credentials not configured");
    }
    testLog("✓ Binance API credentials found");
    
    $binance = new BinanceP2PAPI($apiKey, $secretKey);
    $credentials = $binance->getChatCredentials();
    
    if (isset($credentials['error'])) {
        throw new Exception("Error getting chat credentials: " . $credentials['error']);
    }
    
    $wssUrl = $credentials['data']['chatWssUrl'] ?? null;
    $listenKey = $credentials['data']['listenKey'] ?? null;
    $listenToken = $credentials['data']['listenToken'] ?? null;
    
    if (empty($wssUrl) || empty($listenKey) || empty($listenToken)) {
        throw new Exception("Invalid chat credentials");
    }
    
    testLog("✓ Chat credentials retrieved");
    testLog("  WSS URL: $wssUrl");
    testLog("  Listen Key: $listenKey");
    
    // Test WebSocket client instantiation (without connecting)
    try {
        $wsClient = new BinanceWebSocketClient($wssUrl, $listenKey, $listenToken);
        testLog("✓ WebSocket client instantiated successfully");
    } catch (Exception $e) {
        throw new Exception("Failed to instantiate WebSocket client: " . $e->getMessage());
    }
    
    testLog("✓ WebSocket client is ready to use!");
    testLog("=== Test Complete ===");
    testLog("SUCCESS: All checks passed!");
    
} catch (Exception $e) {
    testLog("ERROR: " . $e->getMessage());
    testLog("Stack trace: " . $e->getTraceAsString());
    exit(1);
}

exit(0);

