import { expect, tap } from '@git.zone/tstest/tapbundle';
import { createServer } from 'node:net';
import type { AddressInfo, Socket } from 'node:net';
import { HomeAssistantNikoHomeControlIntegration, NikoHomeControlClient, NikoHomeControlConfigFlow, NikoHomeControlIntegration, NikoHomeControlMapper, createNikoHomeControlDiscoveryDescriptor, nikoHomeControlProfile, type INikoHomeControlSnapshot, type TNikoHomeControlRawData } from '../../ts/integrations/niko_home_control/index.js';

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

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

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

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

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

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

  expect(snapshot.online).toBeTrue();
  expect(mappedSnapshot.source).toEqual('manual');
  expect(devices[0].integrationDomain).toEqual("niko_home_control");
  expect(devices[0].manufacturer).toEqual("Niko Home Control");
  expect(entities.some((entityArg) => entityArg.integrationDomain === "niko_home_control" && entityArg.platform === "button")).toBeTrue();
});

tap.test('reads and commands a native Niko Home Control TCP JSON controller', async () => {
  const receivedCommands: Record<string, unknown>[] = [];
  const server = createServer((socketArg: Socket) => {
    let buffer = '';
    socketArg.on('data', (chunkArg) => {
      buffer += chunkArg.toString('utf8');
      try {
        const command = JSON.parse(buffer) as Record<string, unknown>;
        buffer = '';
        receivedCommands.push(command);
        const cmd = command.cmd;
        if (cmd === 'listlocations') {
          socketArg.write(`${JSON.stringify({ data: [{ id: 1, name: 'Kitchen' }] })}\n`);
        } else if (cmd === 'listthermostat') {
          socketArg.write(`${JSON.stringify({ data: [{ id: 7, name: 'Thermostat', mode: 5, measured: 201, setpoint: 215, overrule: 0, overruletime: '00:00', ecosave: 0, location: 1 }] })}\n`);
        } else if (cmd === 'listenergy') {
          socketArg.write(`${JSON.stringify({ data: [] })}\n`);
        } else if (cmd === 'systeminfo') {
          socketArg.write(`${JSON.stringify({ data: { serial: 'nhc-test-1', model: 'NHC II' } })}\n`);
        } else if (cmd === 'listactions') {
          socketArg.write(`${JSON.stringify({ data: [
            { id: 10, name: 'Ceiling', type: 2, value1: 50, location: 1 },
            { id: 11, name: 'Shade', type: 4, value1: 0, location: 1 },
            { id: 12, name: 'Dinner', type: 0, value1: 0, location: 1 },
          ] })}\n`);
        }
      } catch {}
    });
  });

  await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve));
  try {
    const port = (server.address() as AddressInfo).port;
    const client = new NikoHomeControlClient({ host: '127.0.0.1', port, timeoutMs: 1000 });
    const snapshot = await client.getSnapshot();

    expect(snapshot.online).toBeTrue();
    expect(snapshot.source).toEqual('tcp');
    expect(snapshot.entities.find((entityArg) => entityArg.id === 'light_10')?.attributes?.brightness).toEqual(127);
    expect(snapshot.entities.find((entityArg) => entityArg.id === 'cover_11')?.state).toEqual('closed');
    expect(snapshot.entities.find((entityArg) => entityArg.id === 'thermostat_7')?.attributes?.targetTemperature).toEqual(21.5);

    const command = await client.execute({ domain: 'light', service: 'turn_on', target: {}, data: { id: 10, brightness: 128 } });
    expect(command.success).toBeTrue();
    await new Promise((resolve) => setTimeout(resolve, 20));
    expect(receivedCommands.some((commandArg) => commandArg.cmd === 'executeactions' && commandArg.id === 10 && commandArg.value1 === 50)).toBeTrue();
  } finally {
    await new Promise<void>((resolve, reject) => server.close((errorArg) => errorArg ? reject(errorArg) : resolve()));
  }
});

tap.test('exposes Niko Home Control runtime, HA alias, and unsupported control without executor', async () => {
  const integration = new NikoHomeControlIntegration();
  const alias = new HomeAssistantNikoHomeControlIntegration();
  expect(alias instanceof NikoHomeControlIntegration).toBeTrue();
  expect(alias.domain).toEqual("niko_home_control");
  expect(integration.status).toEqual("control-runtime");
  expect(nikoHomeControlProfile.metadata.configFlow).toEqual(true);
  expect(nikoHomeControlProfile.metadata.requirements).toEqual([
    "nhc==0.8.0",
  ]);

  const runtime = await integration.setup({ name: "Niko Home Control Runtime", rawData }, {});
  const statusResult = await runtime.callService!({ domain: "niko_home_control", service: 'status', target: {} });
  const refresh = await runtime.callService!({ domain: "niko_home_control", service: 'refresh', target: {} });
  const snapshot = statusResult.data as INikoHomeControlSnapshot;

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

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