import { createServer } from 'node:net';
import { expect, tap } from '@git.zone/tstest/tapbundle';
import { HomeAssistantOnewireIntegration, OnewireClient, OnewireConfigFlow, OnewireIntegration, OnewireMapper, createOnewireDiscoveryDescriptor, onewireProfile, type IOnewireSnapshot, type TOnewireRawData } from '../../ts/integrations/onewire/index.js';

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

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

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

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

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

tap.test('maps 1-Wire raw snapshots to runtime devices and entities', async () => {
  const client = new OnewireClient({ name: "1-Wire Runtime", rawData });
  const snapshot = await client.getSnapshot();
  const mappedSnapshot = OnewireMapper.toSnapshotFromRaw({ name: "1-Wire Runtime" }, rawData);
  const devices = OnewireMapper.toDevices(mappedSnapshot);
  const entities = OnewireMapper.toEntities(mappedSnapshot);

  expect(snapshot.online).toBeTrue();
  expect(mappedSnapshot.source).toEqual('manual');
  expect(devices[0].integrationDomain).toEqual("onewire");
  expect(devices[0].manufacturer).toEqual("1-Wire");
  expect(entities.some((entityArg) => entityArg.integrationDomain === "onewire" && entityArg.platform === "binary_sensor")).toBeTrue();
});

tap.test('polls and writes OWServer data through the native OWNet TCP protocol', async () => {
  const writes: Array<{ path: string; value: string }> = [];
  const values: Record<string, string> = {
    '/system/configuration/version': 'owserver fixture 3.2',
    '/28.FF5C68521604/family': '28',
    '/28.FF5C68521604/type': 'DS18B20',
    '/28.FF5C68521604/temperature': '21.5',
    '/28.FF5C68521604/tempres': '12',
    '/3A.111111111111/family': '3A',
    '/3A.111111111111/type': 'DS2413',
    '/3A.111111111111/sensed.A': '0',
    '/3A.111111111111/sensed.B': '1',
    '/3A.111111111111/PIO.A': '1',
    '/3A.111111111111/PIO.B': '0',
  };
  const server = createServer((socketArg) => {
    let buffer = Buffer.alloc(0);
    socketArg.on('data', (chunkArg) => {
      buffer = Buffer.concat([buffer, Buffer.isBuffer(chunkArg) ? chunkArg : Buffer.from(chunkArg)]);
      while (buffer.length >= 24) {
        const payloadLength = buffer.readInt32BE(4);
        if (buffer.length < 24 + payloadLength) {
          return;
        }
        const type = buffer.readInt32BE(8);
        const payload = buffer.subarray(24, 24 + payloadLength);
        buffer = buffer.subarray(24 + payloadLength);
        if (type === 1) {
          socketArg.end(ownetResponse(0, ''));
        } else if (type === 9) {
          socketArg.end(ownetResponse(0, '/28.FF5C68521604/,/3A.111111111111/'));
        } else if (type === 2) {
          const path = ownetPath(payload);
          const value = values[path];
          socketArg.end(value === undefined ? ownetResponse(-2, '') : ownetResponse(0, value));
        } else if (type === 3) {
          const zeroIndex = payload.indexOf(0);
          const path = payload.subarray(0, zeroIndex).toString('ascii');
          const value = payload.subarray(zeroIndex + 1).toString('ascii');
          values[path] = value;
          writes.push({ path, value });
          socketArg.end(ownetResponse(0, ''));
        }
      }
    });
  });
  await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve));

  try {
    const address = server.address();
    const port = typeof address === 'object' && address ? address.port : 0;
    const client = new OnewireClient({ host: '127.0.0.1', port, timeoutMs: 1000, name: 'OWServer Fixture' });
    const snapshot = await client.getSnapshot(true);
    const command = await client.execute({ domain: 'switch', service: 'turn_off', target: {}, data: { path: '/3A.111111111111/PIO.A' } });

    expect(snapshot.online).toBeTrue();
    expect(snapshot.source).toEqual('tcp');
    expect(snapshot.entities.find((entityArg) => entityArg.id === '28_ff5c68521604_temperature')?.state).toEqual(21.5);
    expect(snapshot.entities.find((entityArg) => entityArg.id === '3a_111111111111_pio_a')?.state).toEqual(true);
    expect(command.success).toBeTrue();
    expect(writes).toEqual([{ path: '/3A.111111111111/PIO.A', value: '0' }]);

    const runtime = await new OnewireIntegration().setup({ host: '127.0.0.1', port, timeoutMs: 1000, name: 'OWServer Fixture' }, {});
    const status = await runtime.callService!({ domain: 'onewire', service: 'status', target: {} });
    expect(status.success).toBeTrue();
    expect((status.data as IOnewireSnapshot).source).toEqual('tcp');
    await runtime.destroy();
  } finally {
    await new Promise<void>((resolve, reject) => server.close((errorArg) => errorArg ? reject(errorArg) : resolve()));
  }
});

tap.test('exposes 1-Wire runtime, HA alias, and unsupported control without executor', async () => {
  const integration = new OnewireIntegration();
  const alias = new HomeAssistantOnewireIntegration();
  expect(alias instanceof OnewireIntegration).toBeTrue();
  expect(alias.domain).toEqual("onewire");
  expect(integration.status).toEqual("control-runtime");
  expect(onewireProfile.metadata.configFlow).toEqual(true);
  expect(onewireProfile.metadata.requirements).toEqual([
    "aio-ownet==0.0.5",
  ]);

  const runtime = await integration.setup({ name: "1-Wire Runtime", rawData }, {});
  const statusResult = await runtime.callService!({ domain: "onewire", service: 'status', target: {} });
  const refresh = await runtime.callService!({ domain: "onewire", service: 'refresh', target: {} });
  const snapshot = statusResult.data as IOnewireSnapshot;

  expect(statusResult.success).toBeTrue();
  expect(refresh.success).toBeTrue();
  expect(snapshot.online).toBeTrue();
  expect((await runtime.devices())[0].name).toEqual("1-Wire Device");

  const command = await runtime.callService!({ domain: "onewire", service: onewireProfile.controlServices?.[0] || 'turn_on', target: {} });
  expect(command.success).toBeFalse();
  expect(command.error!).toContain('requires an injected client.execute() or commandExecutor');
  await runtime.destroy();
});

export default tap.start();

const ownetResponse = (retArg: number, dataArg: string): Buffer => {
  const data = Buffer.from(dataArg, 'ascii');
  const header = Buffer.alloc(24);
  header.writeInt32BE(0, 0);
  header.writeInt32BE(data.length, 4);
  header.writeInt32BE(retArg, 8);
  header.writeInt32BE(0x00000100, 12);
  header.writeInt32BE(data.length, 16);
  header.writeInt32BE(0, 20);
  return Buffer.concat([header, data]);
};

const ownetPath = (payloadArg: Buffer): string => payloadArg.subarray(0, payloadArg.indexOf(0)).toString('ascii');
