import * as net from 'node:net';
import { expect, tap } from '@git.zone/tstest/tapbundle';
import { HomeAssistantMotionmountIntegration, MotionmountClient, MotionmountConfigFlow, MotionmountIntegration, MotionmountMapper, createMotionmountDiscoveryDescriptor, motionmountProfile, type IMotionmountSnapshot, type TMotionmountRawData } from '../../ts/integrations/motionmount/index.js';

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

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

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

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

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

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

  expect(snapshot.online).toBeTrue();
  expect(mappedSnapshot.source).toEqual('manual');
  expect(devices[0].integrationDomain).toEqual("motionmount");
  expect(devices[0].manufacturer).toEqual("Vogel's MotionMount");
  expect(entities.some((entityArg) => entityArg.integrationDomain === "motionmount" && entityArg.platform === "binary_sensor")).toBeTrue();
});

tap.test("exposes Vogel's MotionMount runtime, HA alias, and unsupported control without executor", async () => {
  const integration = new MotionmountIntegration();
  const alias = new HomeAssistantMotionmountIntegration();
  expect(alias instanceof MotionmountIntegration).toBeTrue();
  expect(alias.domain).toEqual("motionmount");
  expect(integration.status).toEqual("control-runtime");
  expect(motionmountProfile.metadata.configFlow).toEqual(true);
  expect(motionmountProfile.metadata.requirements).toEqual([
    "python-MotionMount==2.3.0",
  ]);
  expect((motionmountProfile.metadata.localApi as { implemented: string[] }).implemented.some((entryArg) => entryArg.includes('native TCP line-protocol'))).toBeTrue();

  const runtime = await integration.setup({ name: "Vogel's MotionMount Runtime", rawData }, {});
  const statusResult = await runtime.callService!({ domain: "motionmount", service: 'status', target: {} });
  const refresh = await runtime.callService!({ domain: "motionmount", service: 'refresh', target: {} });
  const snapshot = statusResult.data as IMotionmountSnapshot;

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

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

tap.test('reads Vogel\'s MotionMount TCP state and sends controls', async () => {
  const commands: string[] = [];
  const server = net.createServer((socketArg) => {
    let buffer = '';
    socketArg.on('data', (chunkArg) => {
      buffer += chunkArg.toString('utf8');
      let delimiter = buffer.indexOf('\n');
      while (delimiter >= 0) {
        const line = buffer.slice(0, delimiter).trim();
        buffer = buffer.slice(delimiter + 1);
        if (line) {
          handleMotionmountLine(socketArg, line, commands);
        }
        delimiter = buffer.indexOf('\n');
      }
    });
  });

  await listen(server);
  const address = server.address();
  const port = typeof address === 'object' && address ? address.port : 0;
  try {
    const client = new MotionmountClient({ host: '127.0.0.1', port, timeoutMs: 1000 });
    const snapshot = await client.getSnapshot(true);
    const entities = MotionmountMapper.toEntities(snapshot);
    const extensionCommand = await client.execute({ domain: 'number', service: 'set_value', target: { entityId: 'number.motionmount_extension' }, data: { value: 55 } });
    const turnCommand = await client.execute({ domain: 'number', service: 'set_value', target: { entityId: 'number.motionmount_turn' }, data: { value: 20 } });
    const presetCommand = await client.execute({ domain: 'select', service: 'select_option', target: { entityId: 'select.motionmount_preset' }, data: { option: 'Preset 1' } });
    const runtime = await new MotionmountIntegration().setup({ host: '127.0.0.1', port, timeoutMs: 1000 }, {});
    const refresh = await runtime.callService?.({ domain: 'motionmount', service: 'refresh', target: {} });

    expect(snapshot.online).toBeTrue();
    expect(snapshot.source).toEqual('tcp');
    expect(snapshot.device.serialNumber).toEqual('00:11:22:33:44:55');
    expect(entities.find((entityArg) => entityArg.id.includes('extension'))?.state).toEqual(42);
    expect(entities.find((entityArg) => entityArg.id.includes('turn'))?.state).toEqual(25);
    expect(extensionCommand.success).toBeTrue();
    expect(turnCommand.success).toBeTrue();
    expect(presetCommand.success).toBeTrue();
    expect(commands).toContain('mount/extension/target = 55');
    expect(commands).toContain('mount/turn/target = -20');
    expect(commands).toContain('mount/preset/index = 1');
    expect(refresh?.success).toBeTrue();
    await runtime.destroy();
  } finally {
    await close(server);
  }
});

const handleMotionmountLine = (socketArg: net.Socket, lineArg: string, commandsArg: string[]): void => {
  if (lineArg.includes(' = ') && !lineArg.startsWith('mount/preset/1/name')) {
    commandsArg.push(lineArg);
  }
  const responses: Record<string, string> = {
    mac: 'mac = [001122334455]',
    'configuration/name': 'configuration/name = "Living Room Mount"',
    'mount/extension/current': 'mount/extension/current = 42',
    'mount/turn/current': 'mount/turn/current = -25',
    'mount/isMoving': 'mount/isMoving = 1',
    'mount/extension/target': 'mount/extension/target = 60',
    'mount/turn/target': 'mount/turn/target = -30',
    'mount/errorStatus': 'mount/errorStatus = 0',
    'configuration/authentication/status': 'configuration/authentication/status = [80]',
    'mount/preset/1/active': 'mount/preset/1/active = 1',
    'mount/preset/1/name': 'mount/preset/1/name = "Preset 1"',
    'mount/preset/1/extension': 'mount/preset/1/extension = 42',
    'mount/preset/1/turn': 'mount/preset/1/turn = -25',
  };
  if (lineArg.startsWith('mount/extension/target = ') || lineArg.startsWith('mount/turn/target = ') || lineArg.startsWith('mount/preset/index = ') || lineArg.startsWith('configuration/authentication/pin = ')) {
    socketArg.write('#202\n');
    return;
  }
  if (responses[lineArg]) {
    socketArg.write(`${responses[lineArg]}\n`);
    return;
  }
  if (/^mount\/preset\/[2-7]\/active$/.test(lineArg)) {
    socketArg.write(`${lineArg} = 0\n`);
    return;
  }
  socketArg.write('#404\n');
};

const listen = async (serverArg: net.Server): Promise<void> => {
  await new Promise<void>((resolve, reject) => {
    serverArg.once('error', reject);
    serverArg.listen(0, '127.0.0.1', () => {
      serverArg.off('error', reject);
      resolve();
    });
  });
};

const close = async (serverArg: net.Server): Promise<void> => {
  await new Promise<void>((resolve, reject) => {
    serverArg.close((errorArg) => errorArg ? reject(errorArg) : resolve());
  });
};

export default tap.start();
