import { createServer, type IncomingMessage, type ServerResponse } from 'node:http';
import { expect, tap } from '@git.zone/tstest/tapbundle';
import { HomeAssistantMcpIntegration, McpClient, McpConfigFlow, McpIntegration, McpMapper, createMcpDiscoveryDescriptor, mcpProfile, type IMcpSnapshot, type TMcpRawData } from '../../ts/integrations/mcp/index.js';

const rawData: TMcpRawData = {
  device: {
    id: 'mcp-device-1',
    name: "Model Context Protocol Device",
    manufacturer: "Model Context Protocol",
    model: "Model Context Protocol local integration",
    serialNumber: 'mcp-serial-1',
  },
  entities: [
    { id: 'status', name: 'Status', platform: "sensor", state: true, attributes: { domain: "mcp" } },
  ],
  online: true,
  updatedAt: '2026-01-01T00:00:00.000Z',
  source: 'manual',
};

tap.test('matches manual Model Context Protocol candidates and creates config flow output', async () => {
  const descriptor = createMcpDiscoveryDescriptor();
  const matcher = descriptor.getMatchers().find((matcherArg) => matcherArg.id === 'mcp-manual-match');
  const result = await matcher!.matches({ source: 'manual', id: 'mcp-device-1', name: "Model Context Protocol Device", metadata: { rawData } }, {});

  expect(result.matched).toBeTrue();
  expect(result.candidate?.integrationDomain).toEqual("mcp");

  const validation = await descriptor.getValidators()[0].validate(result.candidate!, {});
  expect(validation.matched).toBeTrue();

  const done = await (await new McpConfigFlow().start(result.candidate!, {})).submit!({});
  expect(done.kind).toEqual('done');
  expect(done.config?.uniqueId).toEqual('mcp-device-1');
  expect(done.config?.rawData).toEqual(rawData);
});

tap.test('maps Model Context Protocol raw snapshots to runtime devices and entities', async () => {
  const client = new McpClient({ name: "Model Context Protocol Runtime", rawData });
  const snapshot = await client.getSnapshot();
  const mappedSnapshot = McpMapper.toSnapshotFromRaw({ name: "Model Context Protocol Runtime" }, rawData);
  const devices = McpMapper.toDevices(mappedSnapshot);
  const entities = McpMapper.toEntities(mappedSnapshot);

  expect(snapshot.online).toBeTrue();
  expect(mappedSnapshot.source).toEqual('manual');
  expect(devices[0].integrationDomain).toEqual("mcp");
  expect(devices[0].manufacturer).toEqual("Model Context Protocol");
  expect(entities.some((entityArg) => entityArg.integrationDomain === "mcp" && entityArg.platform === "sensor")).toBeTrue();
});

tap.test('exposes Model Context Protocol runtime, HA alias, and unsupported control without executor', async () => {
  const integration = new McpIntegration();
  const alias = new HomeAssistantMcpIntegration();
  expect(alias instanceof McpIntegration).toBeTrue();
  expect(alias.domain).toEqual("mcp");
  expect(integration.status).toEqual("control-runtime");
  expect(mcpProfile.metadata.configFlow).toEqual(true);
  expect(mcpProfile.metadata.requirements).toEqual([
    "mcp==1.26.0",
  ]);

  const runtime = await integration.setup({ name: "Model Context Protocol Runtime", rawData }, {});
  const statusResult = await runtime.callService!({ domain: "mcp", service: 'status', target: {} });
  const refresh = await runtime.callService!({ domain: "mcp", service: 'refresh', target: {} });
  const snapshot = statusResult.data as IMcpSnapshot;

  expect(statusResult.success).toBeTrue();
  expect(refresh.success).toBeFalse();
  expect(snapshot.online).toBeTrue();
  expect((await runtime.devices())[0].name).toEqual("Model Context Protocol Device");

  const command = await runtime.callService!({ domain: "mcp", service: mcpProfile.controlServices?.[0] || 'turn_on', target: {} });
  expect(command.success).toBeFalse();
  expect(command.error!).toContain('call_tool requires');
  await runtime.destroy();
});

tap.test('reads and calls MCP streamable HTTP JSON-RPC endpoint', async () => {
  const calls: Array<Record<string, unknown>> = [];
  const server = await startMcpServer('/mcp', calls);
  try {
    const client = new McpClient({ url: server.url, timeoutMs: 1000 });
    const snapshot = await client.getSnapshot(true);
    const call = await client.execute({ domain: 'mcp', service: 'call_tool', target: {}, data: { name: 'turn_light', arguments: { entity_id: 'light.kitchen' } } });
    const runtime = await new McpIntegration().setup({ url: server.url, timeoutMs: 1000 }, {});
    const status = await runtime.callService?.({ domain: 'mcp', service: 'status', target: {} });

    expect(snapshot.online).toBeTrue();
    expect(snapshot.source).toEqual('http');
    expect((snapshot.rawData as { toolCount?: number }).toolCount).toEqual(1);
    expect(McpMapper.toEntities(snapshot).find((entityArg) => entityArg.id.endsWith('tool_count'))?.state).toEqual(1);
    expect(call.success).toBeTrue();
    expect(calls[0].name).toEqual('turn_light');
    expect((status?.data as IMcpSnapshot).online).toBeTrue();
    await runtime.destroy();
  } finally {
    await server.close();
  }
});

const startMcpServer = async (pathArg: string, callsArg: Array<Record<string, unknown>>): Promise<{ url: string; close(): Promise<void> }> => {
  const server = createServer(async (requestArg: IncomingMessage, responseArg: ServerResponse) => {
    if (requestArg.method !== 'POST' || requestArg.url !== pathArg) {
      responseArg.statusCode = 404;
      responseArg.end('not found');
      return;
    }

    const body = JSON.parse(await readRequestBody(requestArg)) as { id?: number; method?: string; params?: Record<string, unknown> };
    if (body.method === 'notifications/initialized') {
      responseArg.statusCode = 202;
      responseArg.end();
      return;
    }
    if (body.method === 'initialize') {
      jsonRpc(responseArg, body.id, { protocolVersion: '2025-03-26', serverInfo: { name: 'Test MCP', version: '1.0.0' }, capabilities: { tools: {} } });
      return;
    }
    if (body.method === 'tools/list') {
      jsonRpc(responseArg, body.id, { tools: [{ name: 'turn_light', description: 'Turn a light on', inputSchema: { type: 'object', properties: { entity_id: { type: 'string' } } } }] });
      return;
    }
    if (body.method === 'tools/call') {
      callsArg.push(body.params || {});
      jsonRpc(responseArg, body.id, { content: [{ type: 'text', text: 'ok' }], structuredContent: { accepted: true } });
      return;
    }

    responseArg.statusCode = 400;
    responseArg.end('unsupported method');
  });

  await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve));
  const address = server.address();
  const port = typeof address === 'object' && address ? address.port : 0;
  return {
    url: `http://127.0.0.1:${port}${pathArg}`,
    close: async () => new Promise<void>((resolve, reject) => server.close((errorArg) => errorArg ? reject(errorArg) : resolve())),
  };
};

const jsonRpc = (responseArg: ServerResponse, idArg: unknown, resultArg: unknown): void => {
  responseArg.setHeader('content-type', 'application/json');
  responseArg.end(JSON.stringify({ jsonrpc: '2.0', id: idArg, result: resultArg }));
};

const readRequestBody = async (requestArg: IncomingMessage): Promise<string> => {
  const chunks: Buffer[] = [];
  for await (const chunk of requestArg) {
    chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
  }
  return Buffer.concat(chunks).toString('utf8');
};

export default tap.start();
