import { expect, tap } from '@git.zone/tstest/tapbundle';
import * as plugins from '../../ts/plugins.js';
import { HomeAssistantNutIntegration, NutClient, NutConfigFlow, NutIntegration, NutMapper, createNutDiscoveryDescriptor, nutProfile, type INutSnapshot, type TNutRawData } from '../../ts/integrations/nut/index.js';

const rawData: TNutRawData = {
  device: {
    id: 'nut-device-1',
    name: "Network UPS Tools (NUT) Device",
    manufacturer: "Network UPS Tools (NUT)",
    model: "Network UPS Tools (NUT) local integration",
    serialNumber: 'nut-serial-1',
  },
  entities: [
    { id: 'status', name: 'Status', platform: "button", state: true, attributes: { domain: "nut" } },
  ],
  online: true,
  updatedAt: '2026-01-01T00:00:00.000Z',
  source: 'manual',
};

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

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

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

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

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

  expect(snapshot.online).toBeTrue();
  expect(mappedSnapshot.source).toEqual('manual');
  expect(devices[0].integrationDomain).toEqual("nut");
  expect(devices[0].manufacturer).toEqual("Network UPS Tools (NUT)");
  expect(entities.some((entityArg) => entityArg.integrationDomain === "nut" && entityArg.platform === "button")).toBeTrue();
});

tap.test('reads and controls Network UPS Tools (NUT) over local TCP', async () => {
  const commands: string[] = [];
  const server = plugins.net.createServer((socketArg) => {
    let buffer = '';
    socketArg.on('data', (chunkArg) => {
      buffer += Buffer.from(chunkArg).toString('utf8');
      let newlineIndex = buffer.indexOf('\n');
      while (newlineIndex >= 0) {
        const command = buffer.slice(0, newlineIndex).trim();
        buffer = buffer.slice(newlineIndex + 1);
        commands.push(command);
        if (command === 'LIST UPS') {
          socketArg.write('BEGIN LIST UPS\nUPS ups "Lab UPS"\nEND LIST UPS\n');
        } else if (command === 'LIST VAR ups') {
          socketArg.write([
            'BEGIN LIST VAR ups',
            'VAR ups ups.status "OL CHRG"',
            'VAR ups battery.charge "91"',
            'VAR ups device.mfr "APC"',
            'VAR ups device.model "Smart-UPS"',
            'VAR ups device.serial "ABC123"',
            'VAR ups outlet.count "1"',
            'VAR ups outlet.1.name "Main"',
            'VAR ups outlet.1.status "on"',
            'VAR ups outlet.1.switchable "yes"',
            'END LIST VAR ups',
            '',
          ].join('\n'));
        } else if (command === 'USERNAME mon') {
          socketArg.write('OK\n');
        } else if (command === 'PASSWORD secret') {
          socketArg.write('OK\n');
        } else if (command === 'LIST CMD ups') {
          socketArg.write([
            'BEGIN LIST CMD ups',
            'CMD ups beeper.mute',
            'CMD ups outlet.1.load.on',
            'CMD ups outlet.1.load.off',
            'CMD ups outlet.1.load.cycle',
            'END LIST CMD ups',
            '',
          ].join('\n'));
        } else if (command === 'INSTCMD ups beeper.mute') {
          socketArg.write('OK\n');
        } else {
          socketArg.write('ERR UNKNOWN-COMMAND\n');
        }
        newlineIndex = buffer.indexOf('\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 NutClient({ host: '127.0.0.1', port, username: 'mon', password: 'secret', timeoutMs: 1000 });
    const snapshot = await client.getSnapshot();

    expect(commands.includes('LIST UPS')).toBeTrue();
    expect(commands.includes('LIST VAR ups')).toBeTrue();
    expect(snapshot.online).toBeTrue();
    expect(snapshot.ups?.manufacturer).toEqual('APC');
    expect(snapshot.vars?.['battery.charge']).toEqual('91');
    expect(snapshot.entities.some((entityArg) => entityArg.id === 'battery_charge' && entityArg.state === 91)).toBeTrue();
    expect(snapshot.entities.some((entityArg) => entityArg.id === 'outlet_1_power' && entityArg.platform === 'switch' && entityArg.state === true)).toBeTrue();

    const commandResult = await client.execute({ domain: 'nut', service: 'press', target: {}, data: { command: 'beeper.mute' } });
    expect(commandResult.success).toBeTrue();
    expect(commands.includes('INSTCMD ups beeper.mute')).toBeTrue();
  } finally {
    await new Promise<void>((resolve, reject) => server.close((errorArg) => errorArg ? reject(errorArg) : resolve()));
  }
});

tap.test('exposes Network UPS Tools (NUT) runtime, HA alias, and unsupported control without executor', async () => {
  const integration = new NutIntegration();
  const alias = new HomeAssistantNutIntegration();
  expect(alias instanceof NutIntegration).toBeTrue();
  expect(alias.domain).toEqual("nut");
  expect(integration.status).toEqual("control-runtime");
  expect(nutProfile.metadata.configFlow).toEqual(true);
  expect(nutProfile.metadata.requirements).toEqual([
    "aionut==4.3.4",
  ]);

  const runtime = await integration.setup({ name: "Network UPS Tools (NUT) Runtime", rawData }, {});
  const statusResult = await runtime.callService!({ domain: "nut", service: 'status', target: {} });
  const refresh = await runtime.callService!({ domain: "nut", service: 'refresh', target: {} });
  const snapshot = statusResult.data as INutSnapshot;

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

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