import { createServer } from 'node:net';
import { expect, tap } from '@git.zone/tstest/tapbundle';
import { HomeAssistantNadIntegration, NadClient, NadConfigFlow, NadIntegration, NadMapper, createNadDiscoveryDescriptor, nadProfile, type INadSnapshot, type TNadRawData } from '../../ts/integrations/nad/index.js';

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

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

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

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

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

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

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

tap.test('reads and controls NAD D7050 over local TCP', async () => {
  const requests: string[] = [];
  const pollHex = '00010202040001020209000102020a0001020203';
  const statusHex = '000102048000010209010001020a000001020302';
  const server = createServer((socketArg) => {
    socketArg.on('data', (chunkArg) => {
      const hex = chunkArg.toString('hex');
      requests.push(hex);
      socketArg.end(Buffer.from(hex === pollHex ? statusHex : hex, 'hex'));
    });
  });

  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 NadClient({ host: '127.0.0.1', port, type: 'TCP', timeoutMs: 1000 });
    const snapshot = await client.getSnapshot(true);
    const command = await client.execute({ domain: 'media_player', service: 'volume_mute', target: {}, data: { mute: true } });

    expect(snapshot.online).toBeTrue();
    expect(snapshot.source).toEqual('tcp');
    expect(snapshot.device.model).toEqual('NAD D7050');
    expect(snapshot.entities[0].state).toEqual('on');
    expect(snapshot.entities[0].attributes?.volume).toEqual(128);
    expect(snapshot.entities[0].attributes?.source).toEqual('Optical 1');
    expect(command.success).toBeTrue();
    expect(requests).toContain(pollHex);
    expect(requests).toContain('0001020a01');
  } finally {
    await new Promise<void>((resolve, reject) => server.close((errorArg) => errorArg ? reject(errorArg) : resolve()));
  }
});

tap.test('reads and controls NAD receiver over local Telnet text protocol', async () => {
  const commands: string[] = [];
  const replies: Record<string, string> = {
    'Main.Power?': 'Main.Power=On',
    'Main.Mute?': 'Main.Mute=Off',
    'Main.Volume?': 'Main.Volume=-40',
    'Main.Source?': 'Main.Source=1',
    'Main.Model?': 'Main.Model=T787',
    'Main.Version?': 'Main.Version=1.0',
    'Main.Source=1': 'Main.Source=1',
  };
  const server = createServer((socketArg) => {
    socketArg.on('data', (chunkArg) => {
      const command = chunkArg.toString('utf8').trim();
      commands.push(command);
      socketArg.end(`\n${replies[command] || `${command}=OK`}\r`);
    });
  });

  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 NadClient({ host: '127.0.0.1', port, type: 'Telnet', timeoutMs: 1000, sources: { '1': 'HDMI 1' } });
    const snapshot = await client.getSnapshot(true);
    const command = await client.execute({ domain: 'media_player', service: 'select_source', target: {}, data: { source: 'HDMI 1' } });

    expect(snapshot.online).toBeTrue();
    expect(snapshot.device.model).toEqual('T787');
    expect(snapshot.entities[0].attributes?.volume).toEqual(-40);
    expect(snapshot.entities[0].attributes?.source).toEqual('HDMI 1');
    expect(command.success).toBeTrue();
    expect(commands).toContain('Main.Power?');
    expect(commands).toContain('Main.Source=1');
  } finally {
    await new Promise<void>((resolve, reject) => server.close((errorArg) => errorArg ? reject(errorArg) : resolve()));
  }
});

tap.test('exposes NAD runtime, HA alias, and unsupported control without executor', async () => {
  const integration = new NadIntegration();
  const alias = new HomeAssistantNadIntegration();
  expect(alias instanceof NadIntegration).toBeTrue();
  expect(alias.domain).toEqual("nad");
  expect(integration.status).toEqual("control-runtime");
  expect(nadProfile.metadata.configFlow).toEqual(false);
  expect(nadProfile.metadata.requirements).toEqual([
    "nad-receiver==0.3.0",
  ]);

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

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

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