import { createServer } from 'node:net';
import { expect, tap } from '@git.zone/tstest/tapbundle';
import { HomeAssistantKeeneticNdms2Integration, KeeneticNdms2Client, KeeneticNdms2ConfigFlow, KeeneticNdms2Integration, KeeneticNdms2Mapper, createKeeneticNdms2DiscoveryDescriptor, keeneticNdms2Profile, type IKeeneticNdms2Snapshot, type TKeeneticNdms2RawData } from '../../ts/integrations/keenetic_ndms2/index.js';

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

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

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

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

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

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

  expect(snapshot.online).toBeTrue();
  expect(mappedSnapshot.source).toEqual('manual');
  expect(devices[0].integrationDomain).toEqual("keenetic_ndms2");
  expect(devices[0].manufacturer).toEqual("Keenetic NDMS2 Router");
  expect(entities.some((entityArg) => entityArg.integrationDomain === "keenetic_ndms2" && entityArg.platform === "binary_sensor")).toBeTrue();
});

tap.test('reads Keenetic NDMS2 router and client presence through native local Telnet', async () => {
  const commands: string[] = [];
  const server = createServer((socketArg) => {
    let stage: 'login' | 'password' | 'command' = 'login';
    let buffer = '';
    socketArg.setEncoding('utf8');
    socketArg.write('Login: ');
    socketArg.on('data', (chunkArg) => {
      buffer += String(chunkArg).replace(/\r/g, '');
      const lines = buffer.split('\n');
      buffer = lines.pop() || '';
      for (const line of lines) {
        const value = line.trim();
        if (stage === 'login') {
          stage = 'password';
          socketArg.write('Password: ');
        } else if (stage === 'password') {
          stage = 'command';
          socketArg.write('\r\n(router)>');
        } else if (value !== 'exit') {
          commands.push(value);
          socketArg.write(keeneticResponse(value));
        }
      }
    });
  });
  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 config = { host: '127.0.0.1', port, username: 'admin', password: 'secret', timeoutMs: 1000, interfaces: ['Home'], name: 'Office Keenetic' };
    const client = new KeeneticNdms2Client(config);
    const snapshot = await client.getSnapshot(true);
    const raw = snapshot.rawData as { routerInfo: { model: string; name: string }; devices: Array<{ mac: string; ip: string; interface: string }> };

    expect(snapshot.online).toBeTrue();
    expect(snapshot.source).toEqual('tcp');
    expect(raw.routerInfo.model).toEqual('Keenetic Giga');
    expect(raw.routerInfo.name).toEqual('Office Router');
    expect(raw.devices.length).toEqual(1);
    expect(raw.devices[0].mac).toEqual('AA:BB:CC:DD:EE:01');
    expect(raw.devices[0].interface).toEqual('Home');
    expect(commands.includes('show version')).toBeTrue();
    expect(commands.includes('show ip arp')).toBeTrue();

    const runtime = await new KeeneticNdms2Integration().setup(config, {});
    const status = await runtime.callService!({ domain: 'keenetic_ndms2', service: 'status', target: {} });
    const entities = await runtime.entities();
    expect(status.success).toBeTrue();
    expect((status.data as IKeeneticNdms2Snapshot).source).toEqual('tcp');
    expect(entities.find((entityArg) => entityArg.id.includes('client_aa_bb_cc_dd_ee_01'))?.attributes?.ipAddress).toEqual('192.168.1.10');
    await runtime.destroy();
  } finally {
    await new Promise<void>((resolve, reject) => server.close((errorArg) => errorArg ? reject(errorArg) : resolve()));
  }
});

tap.test('exposes Keenetic NDMS2 Router runtime, HA alias, and unsupported control without executor', async () => {
  const integration = new KeeneticNdms2Integration();
  const alias = new HomeAssistantKeeneticNdms2Integration();
  expect(alias instanceof KeeneticNdms2Integration).toBeTrue();
  expect(alias.domain).toEqual("keenetic_ndms2");
  expect(integration.status).toEqual("read-only-runtime");
  expect(keeneticNdms2Profile.metadata.configFlow).toEqual(true);
  expect(keeneticNdms2Profile.metadata.requirements).toEqual([
    "ndms2-client==0.1.2",
  ]);

  const runtime = await integration.setup({ name: "Keenetic NDMS2 Router Runtime", rawData }, {});
  const statusResult = await runtime.callService!({ domain: "keenetic_ndms2", service: 'status', target: {} });
  const refresh = await runtime.callService!({ domain: "keenetic_ndms2", service: 'refresh', target: {} });
  const snapshot = statusResult.data as IKeeneticNdms2Snapshot;

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

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

const keeneticResponse = (commandArg: string): string => {
  const responses: Record<string, string[]> = {
    'show version': [
      '          description: Office Router',
      '          title: 4.1.0',
      '          model: Keenetic Giga',
      '          hw_version: A1',
      '          manufacturer: Keenetic Ltd.',
      '          vendor: Keenetic',
      '          region: EU',
    ],
    'show ip hotspot': [],
    'show ip arp': [
      'Phone One 192.168.1.10 aa:bb:cc:dd:ee:01 Home  ',
      'Guest Device 192.168.2.20 aa:bb:cc:dd:ee:02 Guest  ',
    ],
    'show associations': [],
  };
  return `\r\n${commandArg}\r\n${(responses[commandArg] || []).join('\r\n')}\r\n(router)>`;
};

export default tap.start();
