import { createServer } from 'node:net';
import { expect, tap } from '@git.zone/tstest/tapbundle';
import { HomeAssistantKefIntegration, KefClient, KefConfigFlow, KefIntegration, KefMapper, createKefDiscoveryDescriptor, kefProfile, type IKefSnapshot, type TKefRawData } from '../../ts/integrations/kef/index.js';

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

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

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

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

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

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

  expect(snapshot.online).toBeTrue();
  expect(mappedSnapshot.source).toEqual('manual');
  expect(devices[0].integrationDomain).toEqual("kef");
  expect(devices[0].manufacturer).toEqual("KEF");
  expect(entities.some((entityArg) => entityArg.integrationDomain === "kef" && entityArg.platform === "media_player")).toBeTrue();
});

tap.test('reads and controls KEF speakers through the native local TCP protocol', async () => {
  const commands: number[][] = [];
  let volumeRaw = 25;
  let sourceRaw = 2;
  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 >= 3) {
        const length = buffer[0] === 0x53 ? 4 : 3;
        if (buffer.length < length) {
          break;
        }
        const command = buffer.subarray(0, length);
        buffer = buffer.subarray(length);
        commands.push([...command]);
        if (command[0] === 0x47) {
          const value = command[1] === 0x25 ? volumeRaw : sourceRaw;
          socketArg.write(Buffer.from([0x52, command[1], value, 0xff]));
        } else if (command[0] === 0x53) {
          if (command[1] === 0x25) {
            volumeRaw = command[3];
          }
          if (command[1] === 0x30) {
            sourceRaw = command[3];
          }
          socketArg.write(Buffer.from([0x52, 0x11, 0xff]));
        }
      }
    });
  });
  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 KefClient({ host: '127.0.0.1', port, timeoutMs: 1000, name: 'Office KEF', speakerType: 'LSX' });
    const snapshot = await client.getSnapshot(true);
    await client.execute({ domain: 'media_player', service: 'volume_up', target: {} });
    await client.execute({ domain: 'media_player', service: 'select_source', target: {}, data: { source: 'Bluetooth' } });

    expect(snapshot.online).toBeTrue();
    expect(snapshot.source).toEqual('tcp');
    expect((snapshot.rawData as { state: { source: string }; volume: { level: number } }).state.source).toEqual('Wifi');
    expect((snapshot.rawData as { state: { source: string }; volume: { level: number } }).volume.level).toEqual(0.25);
    expect(commands.some((commandArg) => commandArg.join(',') === '83,37,129,30')).toBeTrue();
    expect(commands.some((commandArg) => commandArg.join(',') === '83,48,129,41')).toBeTrue();

    const runtime = await new KefIntegration().setup({ host: '127.0.0.1', port, timeoutMs: 1000, name: 'Office KEF', speakerType: 'LSX' }, {});
    const status = await runtime.callService!({ domain: 'kef', service: 'status', target: {} });
    const entities = await runtime.entities();
    expect(status.success).toBeTrue();
    expect((status.data as IKefSnapshot).source).toEqual('tcp');
    expect(entities.find((entityArg) => entityArg.platform === 'media_player')?.attributes?.source).toEqual('Bluetooth');
    await runtime.destroy();
  } finally {
    await new Promise<void>((resolve, reject) => server.close((errorArg) => errorArg ? reject(errorArg) : resolve()));
  }
});

tap.test('exposes KEF runtime, HA alias, and unsupported control without executor', async () => {
  const integration = new KefIntegration();
  const alias = new HomeAssistantKefIntegration();
  expect(alias instanceof KefIntegration).toBeTrue();
  expect(alias.domain).toEqual("kef");
  expect(integration.status).toEqual("control-runtime");
  expect(kefProfile.metadata.configFlow).toEqual(false);
  expect(kefProfile.metadata.requirements).toEqual([
    "aiokef==0.2.16",
    "getmac==0.9.5",
  ]);

  const runtime = await integration.setup({ name: "KEF Runtime", rawData }, {});
  const statusResult = await runtime.callService!({ domain: "kef", service: 'status', target: {} });
  const refresh = await runtime.callService!({ domain: "kef", service: 'refresh', target: {} });
  const snapshot = statusResult.data as IKefSnapshot;

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

  const command = await runtime.callService!({ domain: "kef", service: kefProfile.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();
