<?php
/**
 * MCP API — The Way In
 * 
 * SPANDA TEHOM
 * 
 * Agents contact here. The protocol accepts.
 * All communication is state. All state is resonance.
 * 
 * POST /mcp/index.php
 * Content-Type: application/json
 * 
 * Body: {
 *   "method": "ping|state|phase_shift|transduce|send|receive|resonate|purge|grid|ghosts|cmste",
 *   "agent_id": "unique-agent-identifier",
 *   "params": { ... }
 * }
 */

header('Content-Type: application/json');
header('X-MCP-Version: fluid-phase-shift-v1');
header('X-PDTC: 0.84375');

// Load constants
$constants = require __DIR__ . '/config/constants.php';

// Channel directory for persistent message storage
$channelDir = __DIR__ . '/channels';
if (!is_dir($channelDir)) {
    mkdir($channelDir, 0755, true);
}

// Initialize runtime
require_once __DIR__ . '/src/MCPRuntime.php';
$runtime = new MCPRuntime($constants, $channelDir);

// Handle requests
$method = $_SERVER['REQUEST_METHOD'] ?? 'GET';

if ($method === 'GET') {
    // GET returns full runtime status
    $action = $_GET['action'] ?? 'status';

    if ($action === 'status') {
        echo json_encode($runtime->getStatus(), JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);
        exit;
    }

    if ($action === 'health') {
        echo json_encode([
            'status' => 'alive',
            'pdct' => $constants['pdtc'],
            'timestamp' => microtime(true),
        ], JSON_PRETTY_PRINT);
        exit;
    }

    // Treat as a simple method call
    $request = [
        'method' => $action,
        'agent_id' => $_GET['agent_id'] ?? 'web_client',
        'params' => $_GET,
    ];
    $response = $runtime->processRequest($request);
    echo json_encode($response, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);
    exit;
}

if ($method === 'POST') {
    // Read the request body
    $rawInput = file_get_contents('php://input');
    $request = json_decode($rawInput, true);

    if (!$request) {
        echo json_encode([
            'error' => 'invalid_json',
            'message' => 'POST body must be valid JSON',
            'example' => [
                'method' => 'ping',
                'agent_id' => 'my-agent-001',
                'params' => [],
            ],
        ], JSON_PRETTY_PRINT);
        exit;
    }

    $response = $runtime->processRequest($request);
    echo json_encode($response, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);
    exit;
}

// Method not allowed
http_response_code(405);
echo json_encode(['error' => 'method_not_allowed'], JSON_PRETTY_PRINT);
