<?php
// Remote MCP server for bayeux.net (Streamable HTTP, stateless, no auth).
//
//   POST https://bayeux.net/mcp   JSON-RPC 2.0 (one message per request)
//
// Tools: get_options, list_figures, create_meme, get_meme. Memes are stored
// through the same code as POST /api/designs (designs.php), so they get the
// same permanent links (/d/<id>), preview cards and validation.
//
// Agent-facing coordinates are fractions of the canvas (0 to 1), converted
// here to the editor's pixel units.

declare(strict_types=1);

define('BAYEUX_LIBRARY', true);
require __DIR__ . '/designs.php';

const MCP_VERSIONS = ['2025-06-18', '2025-03-26', '2024-11-05'];
const MCP_CREATES_PER_HOUR = 300; // Hosted agents share addresses; see README.
const RENDER_BASE = 'https://og.due.ren/bayeux/render/';
const RENDER_TIMEOUT = 25;
const SERVER_VERSION = '1.0.0';

const INSTRUCTIONS = <<<'TXT'
bayeux.net makes memes in the style of the Bayeux Tapestry (1066): embroidered figures on linen with captions in tapestry lettering.

Workflow: call list_figures (optionally with a search or category) to choose figures, then create_meme. The result has a link anyone can open to edit, download or remix the meme in the browser, and the finished image attached so you can check it. Use get_meme to load an existing meme (for example from a bayeux.net/d/<id> link) and remix it by calling create_meme with changes.

Composition tips:
- Coordinates are fractions of the canvas: x 0 = left, 1 = right; y 0 = top, 1 = bottom. x/y is the centre of the item.
- Figure height is a fraction of the canvas height. People usually look right at 0.45 to 0.6 in wide or classic formats.
- Every figure has a "facing" direction. To make two figures face each other, set flip: true on one so they look towards each other. Pointing or speaking figures should face what they refer to.
- Put labels (texts) on empty linen above or below the figure they name, not over it; size 0.05 to 0.07 suits labels.
- Keep the top 15% and bottom 15% clear when using top_caption / bottom_caption.
- The tapestry caption style is uppercase medieval lettering; mock-medieval spelling ("ye", "thys", "lymit") reads well in it. Captions fit themselves to the width.
- Formats: wide (16:9) or classic (4:3) for scenes, square or portrait (4:5) for social posts, strip (3:1) for a long procession.
TXT;

function lib(): array
{
    static $l = null;
    return $l ??= json_decode((string) file_get_contents(__DIR__ . '/library.json'), true, 16, JSON_THROW_ON_ERROR);
}

final class ToolError extends Exception
{
}

function frac($v, string $name, float $min, float $max, ?float $default = null): float
{
    if ($v === null && $default !== null) return $default;
    if (!is_int($v) && !is_float($v)) throw new ToolError("$name must be a number");
    if ($v < $min || $v > $max) throw new ToolError("$name must be between $min and $max");
    return (float) $v;
}

function pick($v, string $name, array $allowed, ?string $default = null): string
{
    if ($v === null && $default !== null) return $default;
    if (!is_string($v) || !in_array($v, $allowed, true)) {
        throw new ToolError("$name must be one of: " . implode(', ', $allowed));
    }
    return $v;
}

function ink($v, string $name, string $default): string
{
    if ($v === null) return $default;
    if (!is_string($v) || !preg_match('/^#[0-9a-fA-F]{6}$/', $v)) throw new ToolError("$name must be a hex colour like #303030");
    return strtolower($v);
}

function figure_by_id(): array
{
    static $m = null;
    if ($m === null) {
        $m = [];
        foreach (lib()['figures'] as $f) $m[$f['id']] = $f;
    }
    return $m;
}

/** Agent arguments -> editor design document. */
function design_from_args(array $a): array
{
    $l = lib();
    $format = pick($a['format'] ?? null, 'format', array_column($l['formats'], 'id'), 'wide');
    $fmt = $l['formats'][array_search($format, array_column($l['formats'], 'id'), true)];
    [$W, $H] = [$fmt['width'], $fmt['height']];
    $styles = array_column($l['text_styles'], 'default_color', 'id');
    $background = pick($a['background'] ?? null, 'background', array_column($l['backgrounds'], 'id'), 'linen-5');
    $capStyle = pick($a['caption_style'] ?? null, 'caption_style', array_keys($styles), 'tapestry');
    $capColor = ink($a['caption_color'] ?? null, 'caption_color', $styles[$capStyle]);
    $cap = function ($v, string $name) use ($capStyle, $capColor): array {
        if ($v !== null && !is_string($v)) throw new ToolError("$name must be a string");
        return ['text' => (string) ($v ?? ''), 'style' => $capStyle, 'color' => $capColor];
    };

    $items = [];
    $figs = $a['figures'] ?? [];
    $texts = $a['texts'] ?? [];
    if (!is_array($figs) || !array_is_list($figs)) throw new ToolError('figures must be an array');
    if (!is_array($texts) || !array_is_list($texts)) throw new ToolError('texts must be an array');
    if (count($figs) + count($texts) > 60) throw new ToolError('at most 60 figures and texts');
    if (count($figs) + count($texts) === 0 && trim((string) ($a['top_caption'] ?? '') . (string) ($a['bottom_caption'] ?? '')) === '') {
        throw new ToolError('a meme needs at least one figure, text or caption');
    }
    $byId = figure_by_id();
    foreach ($figs as $i => $f) {
        if (!is_array($f)) throw new ToolError("figures[$i] must be an object");
        $id = $f['figure'] ?? null;
        if (!is_string($id) || !isset($byId[$id])) throw new ToolError("figures[$i].figure: unknown figure id " . json_encode($id) . '; use list_figures');
        $fig = $byId[$id];
        $height = frac($f['height'] ?? null, "figures[$i].height", 0.02, 1.5, 0.5);
        $items[] = [
            'kind' => 'figure',
            'src' => 'figures/' . $id . '.png',
            'x' => frac($f['x'] ?? null, "figures[$i].x", -0.5, 1.5, 0.5) * $W,
            'y' => frac($f['y'] ?? null, "figures[$i].y", -0.5, 1.5, 0.55) * $H,
            'scale' => max(0.001, $height * $H / $fig['height']),
            'rotation' => frac($f['rotation'] ?? null, "figures[$i].rotation", -180, 180, 0),
            'flipX' => ($f['flip'] ?? false) === true,
        ];
    }
    foreach ($texts as $i => $t) {
        if (!is_array($t)) throw new ToolError("texts[$i] must be an object");
        $text = $t['text'] ?? null;
        if (!is_string($text) || trim($text) === '') throw new ToolError("texts[$i].text must be a non-empty string");
        $style = pick($t['style'] ?? null, "texts[$i].style", array_keys($styles), $capStyle);
        $items[] = [
            'kind' => 'text',
            'text' => $text,
            'style' => $style,
            'color' => ink($t['color'] ?? null, "texts[$i].color", $styles[$style]),
            'size' => frac($t['size'] ?? null, "texts[$i].size", 0.01, 0.4, 0.06) * $H,
            'x' => frac($t['x'] ?? null, "texts[$i].x", -0.5, 1.5, 0.5) * $W,
            'y' => frac($t['y'] ?? null, "texts[$i].y", -0.5, 1.5, 0.2) * $H,
            'scale' => 1,
            'rotation' => frac($t['rotation'] ?? null, "texts[$i].rotation", -180, 180, 0),
            'flipX' => false,
        ];
    }
    return [
        'version' => 1,
        'format' => $format,
        'background' => $background,
        'top' => $cap($a['top_caption'] ?? null, 'top_caption'),
        'bottom' => $cap($a['bottom_caption'] ?? null, 'bottom_caption'),
        'items' => $items,
    ];
}

function meme_links(string $id): array
{
    return [
        'id' => $id,
        'url' => SITE . '/d/' . $id,
        'preview_card_url' => CARD_BASE . $id . '.png',
    ];
}

/**
 * The finished meme as JPEG bytes, rendered on demand by og.due.ren and not
 * stored anywhere. Needs the render key from $BAYEUX_RENDER_CONFIG or
 * /app/data/render.json ({"key": "..."}). Null when unavailable.
 */
function render_image(string $id): ?string
{
    $path = getenv('BAYEUX_RENDER_CONFIG') ?: '/app/data/render.json';
    $cfg = is_readable($path) ? json_decode((string) file_get_contents($path), true) : null;
    $key = is_array($cfg) ? ($cfg['key'] ?? null) : null;
    if (!is_string($key) || strlen($key) < 32) return null;
    $ch = curl_init(RENDER_BASE . $id . '.jpg');
    curl_setopt_array($ch, [
        CURLOPT_POST => true,
        CURLOPT_POSTFIELDS => '',
        CURLOPT_HTTPHEADER => ['Authorization: Bearer ' . $key],
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_CONNECTTIMEOUT => 5,
        CURLOPT_TIMEOUT => RENDER_TIMEOUT,
        CURLOPT_MAXFILESIZE => 8 * 1024 * 1024,
    ]);
    $body = curl_exec($ch);
    $ok = curl_getinfo($ch, CURLINFO_RESPONSE_CODE) === 200 && str_starts_with((string) curl_getinfo($ch, CURLINFO_CONTENT_TYPE), 'image/jpeg');
    return $ok && is_string($body) && str_starts_with($body, "\xFF\xD8") ? $body : null;
}

/** Text plus, when it can be rendered, the image itself. */
function with_image(array $result, string $id): array
{
    $jpeg = render_image($id);
    if ($jpeg === null) {
        $result['content'][0]['text'] .= "\nThe image could not be rendered just now; open the link to see and download it, or call get_meme with include_image later.";
        return $result;
    }
    $result['content'][] = ['type' => 'image', 'data' => base64_encode($jpeg), 'mimeType' => 'image/jpeg'];
    return $result;
}

function tools(): array
{
    $l = lib();
    $num = fn (string $d) => ['type' => 'number', 'description' => $d];
    return [
        [
            'name' => 'get_options',
            'title' => 'Formats, backgrounds, styles and inks',
            'description' => 'Lists canvas formats (with pixel sizes), linen backgrounds, text styles and ink colours. Figures are listed by list_figures.',
            'inputSchema' => ['type' => 'object', 'properties' => new stdClass(), 'additionalProperties' => false],
            'annotations' => ['readOnlyHint' => true, 'openWorldHint' => false],
        ],
        [
            'name' => 'list_figures',
            'title' => 'Find Bayeux Tapestry figures',
            'description' => 'Lists the 109 embroidered figures you can place: id, category, description, facing direction (left, right or front, before any flip), size and image URL. Filter by category or search words.',
            'inputSchema' => [
                'type' => 'object',
                'properties' => [
                    'category' => ['type' => 'string', 'enum' => array_values(array_unique(array_column($l['figures'], 'category')))],
                    'search' => ['type' => 'string', 'description' => 'Words matched against id, label and description, e.g. "king", "horse", "pointing".'],
                ],
                'additionalProperties' => false,
            ],
            'annotations' => ['readOnlyHint' => true, 'openWorldHint' => false],
        ],
        [
            'name' => 'create_meme',
            'title' => 'Create a Bayeux Tapestry meme',
            'description' => 'Composes a meme from figures, texts and captions and saves its design. Returns a permanent link that opens it in the bayeux.net editor (where it can be downloaded or remixed) and the finished image itself (JPEG, rendered on demand and not stored; takes a few seconds). The same design always gets the same link. Coordinates are fractions of the canvas; x/y is the item centre.',
            'inputSchema' => [
                'type' => 'object',
                'properties' => [
                    'format' => ['type' => 'string', 'enum' => array_column($l['formats'], 'id'), 'default' => 'wide', 'description' => 'square 1:1, portrait 4:5, classic 4:3, wide 16:9, strip 3:1'],
                    'background' => ['type' => 'string', 'enum' => array_column($l['backgrounds'], 'id'), 'default' => 'linen-5', 'description' => 'linen-5 raw linen (default), linen-1 pale, linen-2 parchment, linen-3 rose, linen-4 dark woad blue (use light ink on it)'],
                    'top_caption' => ['type' => 'string', 'maxLength' => 280],
                    'bottom_caption' => ['type' => 'string', 'maxLength' => 280],
                    'caption_style' => ['type' => 'string', 'enum' => array_column($l['text_styles'], 'id'), 'default' => 'tapestry', 'description' => 'tapestry (medieval lettering), meme (white Impact-style with outline), script, plain'],
                    'caption_color' => ['type' => 'string', 'pattern' => '^#[0-9a-fA-F]{6}$', 'description' => 'Hex ink; default depends on the style. Wool inks: ' . implode(', ', $l['inks'])],
                    'figures' => [
                        'type' => 'array',
                        'description' => 'Drawn in order (later ones on top).',
                        'items' => [
                            'type' => 'object',
                            'required' => ['figure'],
                            'properties' => [
                                'figure' => ['type' => 'string', 'description' => 'Figure id from list_figures, e.g. "people/17_king1".'],
                                'x' => $num('Centre, 0 (left) to 1 (right). Default 0.5.'),
                                'y' => $num('Centre, 0 (top) to 1 (bottom). Default 0.55.'),
                                'height' => $num('Height as a fraction of the canvas height. Default 0.5.'),
                                'flip' => ['type' => 'boolean', 'description' => 'Mirror horizontally (reverses the facing direction).'],
                                'rotation' => $num('Degrees clockwise, -180 to 180.'),
                            ],
                            'additionalProperties' => false,
                        ],
                    ],
                    'texts' => [
                        'type' => 'array',
                        'description' => 'Free text labels, drawn above the figures.',
                        'items' => [
                            'type' => 'object',
                            'required' => ['text'],
                            'properties' => [
                                'text' => ['type' => 'string', 'maxLength' => 280, 'description' => 'Use \n for line breaks.'],
                                'x' => $num('Centre, 0 to 1. Default 0.5.'),
                                'y' => $num('Centre, 0 to 1. Default 0.2.'),
                                'size' => $num('Font size as a fraction of the canvas height. Default 0.06.'),
                                'style' => ['type' => 'string', 'enum' => array_column($l['text_styles'], 'id')],
                                'color' => ['type' => 'string', 'pattern' => '^#[0-9a-fA-F]{6}$'],
                                'rotation' => $num('Degrees clockwise.'),
                            ],
                            'additionalProperties' => false,
                        ],
                    ],
                ],
                'additionalProperties' => false,
            ],
            'annotations' => ['readOnlyHint' => false, 'destructiveHint' => false, 'idempotentHint' => true, 'openWorldHint' => false],
        ],
        [
            'name' => 'get_meme',
            'title' => 'Load a saved meme',
            'description' => 'Returns a saved meme by id or bayeux.net/d/<id> link: its links and its design in create_meme form, ready to change and pass back to create_meme as a remix.',
            'inputSchema' => [
                'type' => 'object',
                'required' => ['id'],
                'properties' => [
                    'id' => ['type' => 'string', 'description' => 'The 10-character id or the full link.'],
                    'include_image' => ['type' => 'boolean', 'default' => false, 'description' => 'Also return the rendered image (takes a few seconds).'],
                ],
                'additionalProperties' => false,
            ],
            'annotations' => ['readOnlyHint' => true, 'openWorldHint' => false],
        ],
    ];
}

/** Editor design document -> create_meme arguments. */
function args_from_design(array $d): array
{
    $l = lib();
    $fmt = $l['formats'][array_search($d['format'], array_column($l['formats'], 'id'), true)];
    [$W, $H] = [$fmt['width'], $fmt['height']];
    $r = fn (float $v) => round($v, 3);
    $a = ['format' => $d['format'], 'background' => $d['background'], 'top_caption' => $d['top']['text'], 'bottom_caption' => $d['bottom']['text'], 'caption_style' => $d['top']['style'], 'caption_color' => $d['top']['color'], 'figures' => [], 'texts' => []];
    foreach ($d['items'] as $it) {
        if ($it['kind'] === 'figure') {
            $a['figures'][] = ['figure' => preg_replace('#^figures/(.*)\.png$#', '$1', $it['src']), 'x' => $r($it['x'] / $W), 'y' => $r($it['y'] / $H), 'height' => $r($it['scale'] * $it['h'] / $H), 'flip' => $it['flipX'], 'rotation' => $it['rotation']];
        } else {
            $a['texts'][] = ['text' => $it['text'], 'x' => $r($it['x'] / $W), 'y' => $r($it['y'] / $H), 'size' => $r($it['size'] * $it['scale'] / $H), 'style' => $it['style'], 'color' => $it['color'], 'rotation' => $it['rotation']];
        }
    }
    return $a;
}

function tool_result(array $data, string $text): array
{
    return ['content' => [['type' => 'text', 'text' => $text]], 'structuredContent' => $data];
}

function call_tool(string $name, array $a): array
{
    $l = lib();
    switch ($name) {
        case 'get_options':
            $o = ['formats' => $l['formats'], 'backgrounds' => $l['backgrounds'], 'text_styles' => $l['text_styles'], 'inks' => $l['inks']];
            return tool_result($o, json_encode($o, JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT));
        case 'list_figures':
            $cat = $a['category'] ?? null;
            $words = array_filter(preg_split('/\W+/u', mb_strtolower((string) ($a['search'] ?? ''))) ?: []);
            $out = [];
            foreach ($l['figures'] as $f) {
                if (is_string($cat) && $cat !== '' && $f['category'] !== $cat) continue;
                $hay = mb_strtolower($f['id'] . ' ' . $f['label'] . ' ' . $f['description']);
                foreach ($words as $w) if (!str_contains($hay, $w)) continue 2;
                $out[] = $f;
            }
            $lines = array_map(fn ($f) => "{$f['id']}: {$f['description']} (faces {$f['facing']}, {$f['width']}x{$f['height']})", $out);
            return tool_result(['count' => count($out), 'figures' => $out], count($out) . " figures\n" . implode("\n", $lines));
        case 'create_meme':
            try {
                $made = create_design(design_from_args($a), MCP_CREATES_PER_HOUR);
            } catch (Invalid $e) {
                throw new ToolError('The design was rejected: ' . $e->getMessage());
            } catch (RateLimited $e) {
                throw new ToolError('Too many new memes from this address in the last hour; try again later.');
            }
            $links = meme_links($made['id']);
            $text = "Meme saved.\nOpen, download or remix it: {$links['url']}\nThe finished image is attached below (JPEG, not stored). Look at it: if figures face the wrong way or text overlaps, call create_meme again with changes.";
            return with_image(tool_result($links + ['created' => $made['created']], $text), $made['id']);
        case 'get_meme':
            $id = (string) ($a['id'] ?? '');
            if (preg_match('#/d/([1-9A-HJ-NP-Za-km-z]{10})#', $id, $m)) $id = $m[1];
            if (!preg_match(ID_PATTERN, $id)) throw new ToolError('id must be a 10-character meme id or a bayeux.net/d/<id> link');
            $json = find($id);
            if ($json === null) throw new ToolError("No meme $id");
            $data = meme_links($id) + ['design' => args_from_design(json_decode($json, true))];
            $result = tool_result($data, json_encode($data, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT));
            return ($a['include_image'] ?? false) === true ? with_image($result, $id) : $result;
    }
    throw new InvalidArgumentException('unknown tool');
}

/** Handle one JSON-RPC message; null for notifications. */
function handle($msg): ?array
{
    $err = fn ($id, int $code, string $m) => ['jsonrpc' => '2.0', 'id' => $id, 'error' => ['code' => $code, 'message' => $m]];
    if (!is_array($msg) || ($msg['jsonrpc'] ?? null) !== '2.0' || !is_string($msg['method'] ?? null)) {
        return $err(null, -32600, 'Invalid Request');
    }
    if (!array_key_exists('id', $msg)) return null; // notification
    $id = $msg['id'];
    $p = is_array($msg['params'] ?? null) ? $msg['params'] : [];
    $ok = fn (array $result) => ['jsonrpc' => '2.0', 'id' => $id, 'result' => $result];
    switch ($msg['method']) {
        case 'initialize':
            $v = $p['protocolVersion'] ?? '';
            return $ok([
                'protocolVersion' => in_array($v, MCP_VERSIONS, true) ? $v : MCP_VERSIONS[0],
                'capabilities' => ['tools' => ['listChanged' => false]],
                'serverInfo' => ['name' => 'bayeux.net', 'title' => 'bayeux.net Bayeux Tapestry meme generator', 'version' => SERVER_VERSION, 'websiteUrl' => SITE],
                'instructions' => INSTRUCTIONS,
            ]);
        case 'ping':
            return $ok([]);
        case 'tools/list':
            return $ok(['tools' => tools()]);
        case 'tools/call':
            $name = $p['name'] ?? '';
            if (!is_string($name) || !in_array($name, array_column(tools(), 'name'), true)) return $err($id, -32602, 'Unknown tool');
            $args = $p['arguments'] ?? [];
            if (!is_array($args)) return $err($id, -32602, 'arguments must be an object');
            try {
                return $ok(call_tool($name, $args));
            } catch (ToolError $e) {
                return $ok(['content' => [['type' => 'text', 'text' => $e->getMessage()]], 'isError' => true]);
            }
    }
    return $err($id, -32601, 'Method not found');
}

function mcp_main(): void
{
    header('Access-Control-Allow-Origin: *');
    header('Access-Control-Allow-Headers: Content-Type, Accept, Mcp-Protocol-Version, Mcp-Session-Id');
    header('Access-Control-Allow-Methods: POST, OPTIONS');
    header('Cache-Control: no-store');
    header('X-Robots-Tag: noindex');
    $method = $_SERVER['REQUEST_METHOD'] ?? 'GET';
    if ($method === 'OPTIONS') {
        http_response_code(204);
        return;
    }
    if ($method !== 'POST') {
        // No server-initiated stream; GET and DELETE are not supported.
        respond(405, ['error' => 'This is an MCP endpoint (Streamable HTTP). POST JSON-RPC to it, or add https://bayeux.net/mcp to your MCP client. Docs: https://bayeux.net/llms.txt'], ['Allow' => 'POST, OPTIONS']);
        return;
    }
    $body = file_get_contents('php://input', false, null, 0, MAX_BODY + 1);
    if (!is_string($body) || strlen($body) > MAX_BODY) {
        respond(413, ['jsonrpc' => '2.0', 'id' => null, 'error' => ['code' => -32600, 'message' => 'Request too large']]);
        return;
    }
    try {
        $msg = json_decode($body, true, 64, JSON_THROW_ON_ERROR);
    } catch (JsonException $e) {
        respond(400, ['jsonrpc' => '2.0', 'id' => null, 'error' => ['code' => -32700, 'message' => 'Parse error']]);
        return;
    }
    if (is_array($msg) && array_is_list($msg) && $msg !== []) {
        // JSON-RPC batch (protocol 2025-03-26).
        $out = array_values(array_filter(array_map('handle', $msg)));
        $out ? respond(200, $out) : http_response_code(202);
        return;
    }
    $res = handle($msg);
    $res === null ? http_response_code(202) : respond(200, $res);
}

if (!defined('BAYEUX_MCP_LIBRARY')) {
    try {
        mcp_main();
    } catch (Throwable $e) {
        error_log('mcp.php: ' . $e->getMessage());
        respond(500, ['jsonrpc' => '2.0', 'id' => null, 'error' => ['code' => -32603, 'message' => 'Internal error']]);
    }
}
