import assert from 'node:assert/strict';
import test from 'node:test';
import { Client, StreamableHTTPClientTransport } from '@modelcontextprotocol/client';
import { createMcpHandler } from '@modelcontextprotocol/server';
import type { ComputerBackend } from '../src/backend/computer-backend.js';
import { parseConfig } from '../src/config.js';
import { createComputerMcpServerFactory } from '../src/server.js';

const backend: ComputerBackend = {
  async info() {
    return {
      backend: 'x11', sessionType: 'x11', coordinateUnit: 'physical-pixel', coordinateSpaces: ['desktop', 'display'],
      virtualBounds: { x: 0, y: 0, width: 1, height: 1 },
      displays: [{ id: 'D', name: 'D', x: 0, y: 0, width: 1, height: 1, primary: true, pixelWidth: 1, pixelHeight: 1, scale: 1 }],
      capabilities: { observe: true, pointer: true, keyboard: true, text: true },
    };
  },
  async observe() { return { backend: 'x11', mimeType: 'image/png', data: Buffer.from('x'), bytes: 1, capturedAt: '2026-08-19T00:00:00.000Z', region: { x: 0, y: 0, width: 1, height: 1 }, pixelWidth: 1, pixelHeight: 1 };  },
  async act(action) { return { type: action.type, executed: true, executedAt: '2026-08-19T00:00:00.000Z' }; },
};

test('server factory negotiates MCP 2026-07-28 modern era', async () => {
  const handler = createMcpHandler(createComputerMcpServerFactory(parseConfig({}), backend), { legacy: 'reject', responseMode: 'json' });
  const transport = new StreamableHTTPClientTransport(new URL('http://test.local/mcp'), {
    fetch: async (url, init) => handler.fetch(new Request(url, init)),
  });
  const client = new Client({ name: 'test', version: '1.0.0' }, { versionNegotiation: { mode: { pin: '2026-07-28' } } });
  try {
    await client.connect(transport);
    assert.equal(client.getProtocolEra(), 'modern');
    const tools = await client.listTools();
    assert.equal(tools.tools.length, 3);
  } finally {
    await client.close();
    await handler.close();
  }
});
