import { expect, tap } from '@git.zone/tstest/tapbundle';
import { createServer } from 'node:net';
import type { AddressInfo, Socket } from 'node:net';
import { HomeAssistantNibeHeatpumpIntegration, NibeHeatpumpClient, NibeHeatpumpConfigFlow, NibeHeatpumpIntegration, NibeHeatpumpMapper, createNibeHeatpumpDiscoveryDescriptor, nibeHeatpumpProfile, type INibeHeatpumpSnapshot, type TNibeHeatpumpRawData } from '../../ts/integrations/nibe_heatpump/index.js';

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

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

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

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

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

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

  expect(snapshot.online).toBeTrue();
  expect(mappedSnapshot.source).toEqual('manual');
  expect(devices[0].integrationDomain).toEqual("nibe_heatpump");
  expect(devices[0].manufacturer).toEqual("Nibe Heat Pump");
  expect(entities.some((entityArg) => entityArg.integrationDomain === "nibe_heatpump" && entityArg.platform === "binary_sensor")).toBeTrue();
});

tap.test('reads configured NIBE coils through native Modbus TCP', async () => {
  const requests: Array<{ functionCode: number; unitId: number; startingAddress: number; quantity: number }> = [];
  const server = createServer((socketArg: Socket) => {
    socketArg.on('data', (chunkArg) => {
      const request = Buffer.isBuffer(chunkArg) ? chunkArg : Buffer.from(chunkArg);
      const transactionId = request.readUInt16BE(0);
      const unitId = request.readUInt8(6);
      const functionCode = request.readUInt8(7);
      const startingAddress = request.readUInt16BE(8);
      const quantity = request.readUInt16BE(10);
      requests.push({ functionCode, unitId, startingAddress, quantity });

      const pdu = Buffer.from([functionCode, quantity * 2, 0x00, 0xd7]);
      const response = Buffer.alloc(7 + pdu.length);
      response.writeUInt16BE(transactionId, 0);
      response.writeUInt16BE(0, 2);
      response.writeUInt16BE(1 + pdu.length, 4);
      response.writeUInt8(unitId, 6);
      pdu.copy(response, 7);
      socketArg.write(response);
    });
  });

  await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve));
  try {
    const port = (server.address() as AddressInfo).port;
    const client = new NibeHeatpumpClient({
      modbusUrl: `tcp://127.0.0.1:${port}`,
      modbusUnit: 1,
      timeoutMs: 1000,
      coils: [{ address: 40033, name: 'bt50-room-temp-s1-40033', title: 'BT50 Room Temp S1', size: 's16', factor: 10, unit: 'C' }],
    });

    const snapshot = await client.getSnapshot(true);
    expect(snapshot.online).toBeTrue();
    expect(snapshot.source).toEqual('tcp');
    expect(snapshot.entities[0].state).toEqual(21.5);
    expect(snapshot.entities[0].attributes?.address).toEqual(40033);
    expect(requests[0]).toEqual({ functionCode: 3, unitId: 1, startingAddress: 32, quantity: 1 });
  } finally {
    await new Promise<void>((resolve, reject) => server.close((errorArg) => errorArg ? reject(errorArg) : resolve()));
  }
});

tap.test('does not fake unsupported NIBE NibeGW UDP connectivity', async () => {
  const client = new NibeHeatpumpClient({ connectionType: 'nibegw', host: '192.0.2.10' });
  const snapshot = await client.getSnapshot(true);

  expect(snapshot.online).toBeFalse();
  expect(snapshot.error || '').toContain('UDP');
});

tap.test('exposes Nibe Heat Pump runtime, HA alias, and unsupported control without executor', async () => {
  const integration = new NibeHeatpumpIntegration();
  const alias = new HomeAssistantNibeHeatpumpIntegration();
  expect(alias instanceof NibeHeatpumpIntegration).toBeTrue();
  expect(alias.domain).toEqual("nibe_heatpump");
  expect(integration.status).toEqual("control-runtime");
  expect(nibeHeatpumpProfile.metadata.configFlow).toEqual(true);
  expect(nibeHeatpumpProfile.metadata.requirements).toEqual([
    "nibe==2.22.0",
  ]);

  const runtime = await integration.setup({ name: "Nibe Heat Pump Runtime", rawData }, {});
  const statusResult = await runtime.callService!({ domain: "nibe_heatpump", service: 'status', target: {} });
  const refresh = await runtime.callService!({ domain: "nibe_heatpump", service: 'refresh', target: {} });
  const snapshot = statusResult.data as INibeHeatpumpSnapshot;

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

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