import { createServer, type IncomingMessage, type ServerResponse } from 'node:http';
import { expect, tap } from '@git.zone/tstest/tapbundle';
import { HomeAssistantMcpServerIntegration, McpServerClient, McpServerConfigFlow, McpServerIntegration, McpServerMapper, createMcpServerDiscoveryDescriptor, mcpServerProfile, type IMcpServerSnapshot, type TMcpServerRawData } from '../../ts/integrations/mcp_server/index.js';

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

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

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

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

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

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

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

tap.test('exposes Model Context Protocol Server runtime, HA alias, and unsupported control without executor', async () => {
  const integration = new McpServerIntegration();
  const alias = new HomeAssistantMcpServerIntegration();
  expect(alias instanceof McpServerIntegration).toBeTrue();
  expect(alias.domain).toEqual("mcp_server");
  expect(integration.status).toEqual("control-runtime");
  expect(mcpServerProfile.metadata.configFlow).toEqual(true);
  expect(mcpServerProfile.metadata.requirements).toEqual([
    "mcp==1.26.0",
    "aiohttp_sse==2.2.0",
    "anyio==4.10.0",
  ]);

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

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

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

tap.test('reads and calls Home Assistant MCP Server streamable HTTP endpoint', async () => {
  const calls: Array<Record<string, unknown>> = [];
  const server = await startMcpServer('/api/mcp', calls);
  try {
    const client = new McpServerClient({ host: '127.0.0.1', port: server.port, timeoutMs: 1000 });
    const snapshot = await client.getSnapshot(true);
    const call = await client.execute({ domain: 'mcp_server', service: 'call_tool', target: {}, data: { name: 'GetLiveContext', arguments: {} } });
    const runtime = await new McpServerIntegration().setup({ url: server.url, timeoutMs: 1000 }, {});
    const refresh = await runtime.callService?.({ domain: 'mcp_server', service: 'refresh', target: {} });

    expect(snapshot.online).toBeTrue();
    expect(snapshot.source).toEqual('http');
    expect((snapshot.rawData as { toolCount?: number; promptCount?: number; resourceCount?: number }).toolCount).toEqual(1);
    expect((snapshot.rawData as { promptCount?: number }).promptCount).toEqual(1);
    expect((snapshot.rawData as { resourceCount?: number }).resourceCount).toEqual(1);
    expect(McpServerMapper.toEntities(snapshot).find((entityArg) => entityArg.id.endsWith('resource_count'))?.state).toEqual(1);
    expect(call.success).toBeTrue();
    expect(calls[0].name).toEqual('GetLiveContext');
    expect(refresh?.success).toBeTrue();
    await runtime.destroy();
  } finally {
    await server.close();
  }
});

const startMcpServer = async (pathArg: string, callsArg: Array<Record<string, unknown>>): Promise<{ url: string; port: number; 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: 'home-assistant', version: '2026.1.0' }, capabilities: { tools: {}, prompts: {}, resources: {} } });
      return;
    }
    if (body.method === 'tools/list') {
      jsonRpc(responseArg, body.id, { tools: [{ name: 'GetLiveContext', description: 'Return Assist context', inputSchema: { type: 'object', properties: {} } }] });
      return;
    }
    if (body.method === 'prompts/list') {
      jsonRpc(responseArg, body.id, { prompts: [{ name: 'Assist', description: 'Default Assist prompt' }] });
      return;
    }
    if (body.method === 'resources/list') {
      jsonRpc(responseArg, body.id, { resources: [{ uri: 'homeassistant://assist/context-snapshot', name: 'assist_context_snapshot', title: 'Assist context snapshot', mimeType: 'text/plain' }] });
      return;
    }
    if (body.method === 'tools/call') {
      callsArg.push(body.params || {});
      jsonRpc(responseArg, body.id, { content: [{ type: 'text', text: '{"success":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}`,
    port,
    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();
