import { createServer } from 'node:net';
import type { AddressInfo, Socket } from 'node:net';
import { expect, tap } from '@git.zone/tstest/tapbundle';
import { HomeAssistantKaleidescapeIntegration, KaleidescapeClient, KaleidescapeConfigFlow, KaleidescapeIntegration, KaleidescapeMapper, createKaleidescapeDiscoveryDescriptor, kaleidescapeProfile, type IKaleidescapeSnapshot, type TKaleidescapeRawData } from '../../ts/integrations/kaleidescape/index.js';

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

const startKaleidescapeServer = async () => {
  const received: string[] = [];
  const responses: Record<string, string[]> = {
    GET_DEVICE_INFO: ['unused', '#000000123456', '01', '192.168.001.050'],
    GET_SYSTEM_VERSION: ['13', '10.0.0'],
    GET_DEVICE_TYPE_NAME: ['Strato C'],
    GET_NUM_ZONES: ['1', '1'],
    GET_DEVICE_POWER_STATE: ['1', '1'],
    GET_SYSTEM_READINESS_STATE: ['0'],
    GET_FRIENDLY_NAME: ['Theater'],
    GET_UI_STATE: ['7', '0', '0', '0'],
    GET_HIGHLIGHTED_SELECTION: ['movie-handle'],
    GET_PLAY_STATUS: ['2', '1', '1', '7200', '120', '1', '600', '120'],
    GET_MOVIE_LOCATION: ['3'],
    GET_VIDEO_MODE: ['0', '0', '27'],
    GET_VIDEO_COLOR: ['2', '4', '30', '3'],
    GET_SCREEN_MASK: ['5', '0', '0', '5', '0', '0'],
    GET_CINEMASCAPE_MODE: ['1'],
  };
  const server = createServer((socketArg: Socket) => {
    let buffer = '';
    socketArg.on('data', (chunkArg: Buffer) => {
      buffer += chunkArg.toString('latin1');
      let index = buffer.indexOf('\n');
      while (index >= 0) {
        const line = buffer.slice(0, index).trim();
        buffer = buffer.slice(index + 1);
        const match = line.match(/^01\/([0-9])\/([^:]+):(.*)$/);
        if (match) {
          const seq = match[1];
          const requestName = match[2];
          received.push(requestName);
          const responseName = requestName.startsWith('GET_') ? requestName.slice(4) : '';
          const fields = responses[requestName] || [];
          const body = responseName ? `${responseName}:${fields.join(':')}:` : '';
          socketArg.write(`01/${seq}/000:${body}/0\n`, 'latin1');
        }
        index = buffer.indexOf('\n');
      }
    });
  });

  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 Kaleidescape candidates and creates config flow output', async () => {
  const descriptor = createKaleidescapeDiscoveryDescriptor();
  const matcher = descriptor.getMatchers().find((matcherArg) => matcherArg.id === 'kaleidescape-manual-match');
  const result = await matcher!.matches({ source: 'manual', id: 'kaleidescape-device-1', name: "Kaleidescape Device", metadata: { rawData } }, {});

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

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

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

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

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

tap.test('polls and controls Kaleidescape through the System Control Protocol TCP API', async () => {
  const { server, port, received } = await startKaleidescapeServer();
  try {
    const client = new KaleidescapeClient({ host: '127.0.0.1', port, name: 'Theater' });
    const snapshot = await client.getSnapshot(true);
    const command = await client.execute({ domain: 'media_player', service: 'media_pause', target: {} });

    expect(snapshot.source).toEqual('tcp');
    expect(snapshot.device.model).toEqual('Strato C');
    expect(snapshot.device.serialNumber).toEqual('000000123456');
    expect(snapshot.entities.find((entityArg) => entityArg.id === 'media_player')?.state).toEqual('playing');
    expect(snapshot.entities.find((entityArg) => entityArg.id === 'video_mode')?.state).toEqual('3840x2160p23976_16:9');
    expect(command.success).toBeTrue();
    expect(received.includes('GET_DEVICE_INFO')).toBeTrue();
    expect(received.includes('PAUSE')).toBeTrue();
  } finally {
    await new Promise<void>((resolve) => server.close(() => resolve()));
  }
});

tap.test('exposes Kaleidescape runtime, HA alias, and unsupported control without executor', async () => {
  const integration = new KaleidescapeIntegration();
  const alias = new HomeAssistantKaleidescapeIntegration();
  expect(alias instanceof KaleidescapeIntegration).toBeTrue();
  expect(alias.domain).toEqual("kaleidescape");
  expect(integration.status).toEqual("control-runtime");
  expect(kaleidescapeProfile.metadata.configFlow).toEqual(true);
  expect(kaleidescapeProfile.metadata.requirements).toEqual([
    "pykaleidescape==1.1.5",
  ]);

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

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

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