import * as net from 'node:net';
import { expect, tap } from '@git.zone/tstest/tapbundle';
import { HomeAssistantMaxcubeIntegration, MaxcubeClient, MaxcubeConfigFlow, MaxcubeIntegration, MaxcubeMapper, createMaxcubeDiscoveryDescriptor, maxcubeProfile, type IMaxcubeSnapshot, type TMaxcubeRawData } from '../../ts/integrations/maxcube/index.js';

const rawData: TMaxcubeRawData = {
  device: {
    id: 'maxcube-device-1',
    name: "eQ-3 MAX! Device",
    manufacturer: "eQ-3 MAX!",
    model: "eQ-3 MAX! local integration",
    serialNumber: 'maxcube-serial-1',
  },
  entities: [
    { id: 'status', name: 'Status', platform: "binary_sensor", state: true, attributes: { domain: "maxcube" } },
  ],
  online: true,
  updatedAt: '2026-01-01T00:00:00.000Z',
  source: 'manual',
};

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

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

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

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

tap.test('maps eQ-3 MAX! raw snapshots to runtime devices and entities', async () => {
  const client = new MaxcubeClient({ name: "eQ-3 MAX! Runtime", rawData });
  const snapshot = await client.getSnapshot();
  const mappedSnapshot = MaxcubeMapper.toSnapshotFromRaw({ name: "eQ-3 MAX! Runtime" }, rawData);
  const devices = MaxcubeMapper.toDevices(mappedSnapshot);
  const entities = MaxcubeMapper.toEntities(mappedSnapshot);

  expect(snapshot.online).toBeTrue();
  expect(mappedSnapshot.source).toEqual('manual');
  expect(devices[0].integrationDomain).toEqual("maxcube");
  expect(devices[0].manufacturer).toEqual("eQ-3 MAX!");
  expect(entities.some((entityArg) => entityArg.integrationDomain === "maxcube" && entityArg.platform === "binary_sensor")).toBeTrue();
});

tap.test('exposes eQ-3 MAX! runtime, HA alias, and unsupported control without executor', async () => {
  const integration = new MaxcubeIntegration();
  const alias = new HomeAssistantMaxcubeIntegration();
  expect(alias instanceof MaxcubeIntegration).toBeTrue();
  expect(alias.domain).toEqual("maxcube");
  expect(integration.status).toEqual("control-runtime");
  expect(maxcubeProfile.metadata.configFlow).toEqual(false);
  expect(maxcubeProfile.metadata.requirements).toEqual([
    "maxcube-api==0.4.3",
  ]);

  const runtime = await integration.setup({ name: "eQ-3 MAX! Runtime", rawData }, {});
  const statusResult = await runtime.callService!({ domain: "maxcube", service: 'status', target: {} });
  const refresh = await runtime.callService!({ domain: "maxcube", service: 'refresh', target: {} });
  const snapshot = statusResult.data as IMaxcubeSnapshot;

  expect(statusResult.success).toBeTrue();
  expect(refresh.success).toBeFalse();
  expect(snapshot.online).toBeTrue();
  expect((await runtime.devices())[0].name).toEqual("eQ-3 MAX! Device");

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

tap.test('reads MAX! Cube TCP state and sends thermostat commands', async () => {
  const sentRadioMessages: string[] = [];
  const server = net.createServer((socket) => {
    for (const line of maxcubeStateLines()) {
      socket.write(`${line}\r\n`);
    }

    let buffer = '';
    socket.on('data', (chunkArg) => {
      buffer += chunkArg.toString('utf8');
      let delimiter = buffer.indexOf('\r\n');
      while (delimiter >= 0) {
        const line = buffer.slice(0, delimiter);
        buffer = buffer.slice(delimiter + 2);
        if (line.startsWith('s:')) {
          sentRadioMessages.push(Buffer.from(line.slice(2), 'base64').toString('hex').toUpperCase());
          socket.write('S:00,0,0,0\r\n');
        }
        delimiter = buffer.indexOf('\r\n');
      }
    });
  });

  await listen(server);
  const address = server.address();
  const port = typeof address === 'object' && address ? address.port : 0;
  try {
    const client = new MaxcubeClient({ host: '127.0.0.1', port, timeoutMs: 1000 });
    const snapshot = await client.getSnapshot(true);
    const entities = MaxcubeMapper.toEntities(snapshot);
    const command = await client.execute({ domain: 'climate', service: 'set_temperature', target: {}, data: { rfAddress: '123456', temperature: 22 } });
    const runtime = await new MaxcubeIntegration().setup({ host: '127.0.0.1', port, timeoutMs: 1000 }, {});
    const refresh = await runtime.callService?.({ domain: 'maxcube', service: 'refresh', target: {} });

    expect(snapshot.online).toBeTrue();
    expect(snapshot.source).toEqual('tcp');
    const parsedRawData = snapshot.rawData as { devices?: unknown[] } | undefined;
    expect(parsedRawData?.devices?.length).toEqual(2);
    expect(entities.find((entityArg) => entityArg.platform === 'climate')?.state).toEqual('heat');
    expect(entities.find((entityArg) => entityArg.id.includes('_window'))?.state).toBeTrue();
    expect(command.success).toBeTrue();
    expect(sentRadioMessages[0]).toEqual('000440000000123456016C');
    expect(refresh?.success).toBeTrue();
    await runtime.destroy();
  } finally {
    await close(server);
  }
});

const maxcubeStateLines = (): string[] => [
  'H:JEQ0123456,ABCDEF,0113',
  `M:00,00,${maxcubeMetadataPayload()}`,
  `C:123456,${maxcubeConfigPayload()}`,
  `L:${maxcubeLivePayload()}`,
];

const maxcubeMetadataPayload = (): string => {
  const roomName = Buffer.from('Living', 'utf8');
  const thermostatName = Buffer.from('Radiator', 'utf8');
  const windowName = Buffer.from('Window', 'utf8');
  const data = Buffer.concat([
    Buffer.from([0, 0, 1, 1, roomName.length]),
    roomName,
    Buffer.from([0x12, 0x34, 0x56, 2, 1, 0x12, 0x34, 0x56]),
    Buffer.from('ABC1234567', 'utf8'),
    Buffer.from([thermostatName.length]),
    thermostatName,
    Buffer.from([1, 4, 0x65, 0x43, 0x21]),
    Buffer.from('WIN1234567', 'utf8'),
    Buffer.from([windowName.length]),
    windowName,
    Buffer.from([1]),
  ]);
  return data.toString('base64');
};

const maxcubeConfigPayload = (): string => {
  const data = Buffer.alloc(30);
  data[18] = 42;
  data[19] = 34;
  data[20] = 60;
  data[21] = 10;
  return data.toString('base64');
};

const maxcubeLivePayload = (): string => {
  const thermostat = Buffer.from([11, 0x12, 0x34, 0x56, 0, 0, 1, 37, 42, 0, 205, 0]);
  const window = Buffer.from([6, 0x65, 0x43, 0x21, 0, 0, 1]);
  return Buffer.concat([thermostat, window]).toString('base64');
};

const listen = async (serverArg: net.Server): Promise<void> => {
  await new Promise<void>((resolve, reject) => {
    serverArg.once('error', reject);
    serverArg.listen(0, '127.0.0.1', () => {
      serverArg.off('error', reject);
      resolve();
    });
  });
};

const close = async (serverArg: net.Server): Promise<void> => {
  await new Promise<void>((resolve, reject) => {
    serverArg.close((errorArg) => errorArg ? reject(errorArg) : resolve());
  });
};

export default tap.start();
