import { createServer } from 'node:net';
import type { AddressInfo, Socket } from 'node:net';
import { expect, tap } from '@git.zone/tstest/tapbundle';
import { HomeAssistantJvcProjectorIntegration, JvcProjectorClient, JvcProjectorConfigFlow, JvcProjectorIntegration, JvcProjectorMapper, createJvcProjectorDiscoveryDescriptor, jvcProjectorProfile, type IJvcProjectorSnapshot, type TJvcProjectorRawData } from '../../ts/integrations/jvc_projector/index.js';

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

const startJvcProjectorServer = async () => {
  const received: string[] = [];
  const pjReq = Buffer.from('PJREQ', 'latin1');
  const pjAck = Buffer.from('PJACK', 'latin1');
  const headAck = Buffer.from([0x06, 0x89, 0x01]);
  const headRes = Buffer.from([0x40, 0x89, 0x01]);
  const newline = Buffer.from('\n', 'latin1');
  const responses: Record<string, string> = {
    MD: 'B5A3',
    LSMA: 'AA BB CC DD EE FF',
    IFSV: '1.23',
    PW: '1',
    SC: '1',
    IP: '6',
    IFLT: '000A',
  };
  const knownCodes = Object.keys(responses).concat('RC').sort((leftArg, rightArg) => rightArg.length - leftArg.length);
  const server = createServer((socketArg: Socket) => {
    let authenticated = false;
    let buffer = Buffer.alloc(0);
    socketArg.write(Buffer.from('PJ_OK', 'latin1'));

    const handleFrame = (frameArg: Buffer) => {
      const isOperation = frameArg[0] === 0x21;
      const body = frameArg.subarray(3, frameArg.length - 1).toString('latin1');
      const code = knownCodes.find((codeArg) => body.startsWith(codeArg));
      if (!code) {
        return;
      }
      received.push(`${isOperation ? 'op' : 'ref'}:${body}`);
      const prefix = Buffer.from(code.slice(0, 2), 'latin1');
      socketArg.write(Buffer.concat([headAck, prefix, newline]));
      if (!isOperation) {
        socketArg.write(Buffer.concat([headRes, prefix, Buffer.from(responses[code], 'latin1'), newline]));
      }
    };

    socketArg.on('data', (chunkArg: Buffer) => {
      buffer = Buffer.concat([buffer, chunkArg]);
      if (!authenticated && buffer.length >= pjReq.length && buffer.subarray(0, pjReq.length).equals(pjReq)) {
        received.push('PJREQ');
        buffer = buffer.subarray(pjReq.length);
        authenticated = true;
        socketArg.write(pjAck);
      }
      let index = buffer.indexOf(0x0a);
      while (index >= 0) {
        const frame = buffer.subarray(0, index + 1);
        buffer = buffer.subarray(index + 1);
        handleFrame(frame);
        index = buffer.indexOf(0x0a);
      }
    });
  });

  await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve));
  return { server, port: (server.address() as AddressInfo).port, received };
};

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

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

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

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

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

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

tap.test('polls and controls JVC Projector through the pyjvcprojector TCP protocol', async () => {
  const { server, port, received } = await startJvcProjectorServer();
  try {
    const client = new JvcProjectorClient({ host: '127.0.0.1', port, name: 'Theater Projector' });
    const snapshot = await client.getSnapshot(true);
    const command = await client.execute({ domain: 'remote', service: 'send_command', target: {}, data: { command: ['menu'] } });

    expect(snapshot.source).toEqual('tcp');
    expect(snapshot.device.model).toEqual('B5A3');
    expect(snapshot.entities.find((entityArg) => entityArg.id === 'input')?.state).toEqual('hdmi1');
    expect(snapshot.entities.find((entityArg) => entityArg.id === 'light_time')?.state).toEqual(10);
    expect(command.success).toBeTrue();
    expect(received.some((entryArg) => entryArg === 'ref:MD')).toBeTrue();
    expect(received.some((entryArg) => entryArg === 'op:RC732E')).toBeTrue();
  } finally {
    await new Promise<void>((resolve) => server.close(() => resolve()));
  }
});

tap.test('exposes JVC Projector runtime, HA alias, and unsupported control without executor', async () => {
  const integration = new JvcProjectorIntegration();
  const alias = new HomeAssistantJvcProjectorIntegration();
  expect(alias instanceof JvcProjectorIntegration).toBeTrue();
  expect(alias.domain).toEqual("jvc_projector");
  expect(integration.status).toEqual("control-runtime");
  expect(jvcProjectorProfile.metadata.configFlow).toEqual(true);
  expect(jvcProjectorProfile.metadata.requirements).toEqual([
    "pyjvcprojector==2.0.6",
  ]);

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

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

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