import { expect, tap } from '@git.zone/tstest/tapbundle';
import * as plugins from '../../ts/plugins.js';
import { HomeAssistantNetioIntegration, NetioClient, NetioConfigFlow, NetioIntegration, NetioMapper, createNetioDiscoveryDescriptor, netioProfile, type INetioSnapshot, type TNetioRawData } from '../../ts/integrations/netio/index.js';

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

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

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

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

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

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

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

tap.test('polls and controls Netio outlets over local telnet TCP', async () => {
  let states = '1010';
  const commands: string[] = [];
  const server = plugins.net.createServer((socketArg) => {
    let buffer = '';
    socketArg.write('100 HELLO\r\n');
    socketArg.on('data', (chunkArg) => {
      buffer += Buffer.isBuffer(chunkArg) ? chunkArg.toString('utf8') : Buffer.from(chunkArg).toString('utf8');
      let newlineIndex = buffer.search(/\r?\n/);
      while (newlineIndex >= 0) {
        const line = buffer.slice(0, newlineIndex).trim();
        buffer = buffer.slice(buffer[newlineIndex] === '\r' && buffer[newlineIndex + 1] === '\n' ? newlineIndex + 2 : newlineIndex + 1);
        commands.push(line);
        if (line.startsWith('login ')) {
          socketArg.write('250 OK\r\n');
        } else if (line === 'port list') {
          socketArg.write(`250 ${states}\r\n`);
        } else if (line.startsWith('port list ')) {
          const mask = line.slice('port list '.length);
          states = states.split('').map((valueArg, indexArg) => mask[indexArg] === 'u' ? valueArg : mask[indexArg]).join('');
          socketArg.write(`250 ${states}\r\n`);
        } else {
          socketArg.write('500 ERROR\r\n');
        }
        newlineIndex = buffer.search(/\r?\n/);
      }
    });
  });

  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 NetioClient({ host: '127.0.0.1', port, username: 'admin', password: 'secret', outlets: { '1': 'Router', '2': 'NAS' }, timeoutMs: 1000 });
    const snapshot = await client.getSnapshot();

    expect(snapshot.online).toBeTrue();
    expect(snapshot.source).toEqual('tcp');
    expect(snapshot.entities.find((entityArg) => entityArg.id === 'outlet_1')?.state).toBeTrue();
    expect(snapshot.entities.find((entityArg) => entityArg.id === 'outlet_2')?.name).toEqual('NAS');

    const result = await client.execute({ domain: 'netio', service: 'turn_off', target: {}, data: { outlet: 1 } });
    expect(result.success).toBeTrue();
    expect(states).toEqual('0010');
    expect(commands).toContain('port list 0uuu');
  } finally {
    await new Promise<void>((resolve, reject) => server.close((errorArg) => errorArg ? reject(errorArg) : resolve()));
  }
});

tap.test('exposes Netio runtime, HA alias, and unsupported control without executor', async () => {
  const integration = new NetioIntegration();
  const alias = new HomeAssistantNetioIntegration();
  expect(alias instanceof NetioIntegration).toBeTrue();
  expect(alias.domain).toEqual("netio");
  expect(integration.status).toEqual("control-runtime");
  expect(netioProfile.metadata.configFlow).toEqual(false);
  expect(netioProfile.metadata.requirements).toEqual([
    "pynetio==0.1.9.1",
  ]);

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

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

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