#!/usr/bin/env php
<?php
/**
 * MCP Memory Server - stdio Transport Wrapper
 * 
 * Allows the MCP server to be tested with the MCP Inspector
 * by providing stdin/stdout JSON-RPC transport.
 * 
 * Usage:
 *   npx @modelcontextprotocol/inspector php bin/mcp-stdio
 */

chdir(__DIR__ . '/..');
require_once __DIR__ . '/../includes/bootstrap.inc.php';

use Mcp\McpServer;

// Create server
$server = new McpServer(APPLICATION_NAME, APPLICATION_VERSION);

// Create ArcadeDB client from settings
global $SETTINGS;
$arcadedb = new ArcadeDB(
    $SETTINGS ? $SETTINGS->getString('arcadedb', 'host', 'localhost') : 'localhost',
    $SETTINGS ? $SETTINGS->getInt('arcadedb', 'port', 2480) : 2480,
    $SETTINGS ? $SETTINGS->getString('arcadedb', 'user', 'root') : 'root',
    $SETTINGS ? $SETTINGS->getString('arcadedb', 'pass', '') : ''
);

// Create and register memory graph tools
$database = $SETTINGS ? $SETTINGS->getString('arcadedb', 'database', 'memory') : 'memory';
$memoryGraph = new MemoryGraph($arcadedb, $database);
$server->register($memoryGraph);

// Log to stderr (Inspector will capture this)
function debug(string $message): void
{
    fwrite(STDERR, "[MCP] " . $message . "\n");
}

debug("MCP Memory Server started (stdio transport)");

// Main loop - read from stdin (blocking), process, write to stdout
while (($line = fgets(STDIN)) !== false) {
    $line = trim($line);
    if (empty($line)) {
        continue;
    }
    
    debug("Received: " . substr($line, 0, 100) . (strlen($line) > 100 ? '...' : ''));
    
    $request = json_decode($line, true);
    if ($request === null) {
        debug("Invalid JSON received");
        continue;
    }
    
    // Handle the request
    $response = $server->handleRequest($request);
    
    if (!empty($response)) {
        $output = json_encode($response, JSON_UNESCAPED_SLASHES);
        debug("Sending: " . substr($output, 0, 100) . (strlen($output) > 100 ? '...' : ''));
        fwrite(STDOUT, $output . "\n");
        fflush(STDOUT);
    }
}

debug("MCP Memory Server stopped");
