import { expect, tap } from '@git.zone/tstest/tapbundle';
import * as plugins from '../../ts/plugins.js';
import { HomeAssistantLgSoundbarIntegration, LgSoundbarClient, LgSoundbarConfigFlow, LgSoundbarIntegration, LgSoundbarMapper, createLgSoundbarDiscoveryDescriptor, lgSoundbarProfile, type ILgSoundbarSnapshot, type TLgSoundbarRawData } from '../../ts/integrations/lg_soundbar/index.js';

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

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

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

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

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

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

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

tap.test('polls and controls LG Soundbars through native encrypted TCP', async () => {
  const server = await startLgSoundbarTestServer();
  try {
    const client = new LgSoundbarClient({ host: '127.0.0.1', port: server.port, timeoutMs: 500 });
    const snapshot = await client.getSnapshot(true);
    const entity = snapshot.entities.find((entityArg) => entityArg.id === 'media_player');

    expect(snapshot.source).toEqual('tcp');
    expect(snapshot.device.serialNumber).toEqual('soundbar-uuid');
    expect(entity?.state).toEqual('playing');
    expect(entity?.attributes?.volumeLevel).toEqual(0.5);
    expect(entity?.attributes?.source).toEqual('Bluetooth');
    expect(entity?.attributes?.soundMode).toEqual('Bass Blast');

    const result = await client.execute({ domain: 'media_player', service: 'media_pause', target: {} });
    expect(result.success).toBeTrue();
    expect(server.received.some((packetArg) => packetArg.cmd === 'set' && packetArg.msg === 'PLAY_INFO' && (packetArg.data as Record<string, unknown>).i_play_ctrl === 1)).toBeTrue();
  } finally {
    await server.close();
  }
});

tap.test('exposes LG Soundbars runtime, HA alias, and unsupported control without executor', async () => {
  const integration = new LgSoundbarIntegration();
  const alias = new HomeAssistantLgSoundbarIntegration();
  expect(alias instanceof LgSoundbarIntegration).toBeTrue();
  expect(alias.domain).toEqual("lg_soundbar");
  expect(integration.status).toEqual("control-runtime");
  expect(lgSoundbarProfile.metadata.configFlow).toEqual(true);
  expect(lgSoundbarProfile.metadata.requirements).toEqual([
    "temescal==0.5",
  ]);

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

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

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

interface ILgSoundbarTestServer {
  port: number;
  received: Record<string, unknown>[];
  close(): Promise<void>;
}

async function startLgSoundbarTestServer(): Promise<ILgSoundbarTestServer> {
  const received: Record<string, unknown>[] = [];
  const sockets = new Set<plugins.net.Socket>();
  const server = plugins.net.createServer((socket) => {
    sockets.add(socket);
    socket.once('close', () => sockets.delete(socket));
    let buffer: Buffer<ArrayBufferLike> = Buffer.alloc(0);
    socket.on('data', (chunkArg) => {
      buffer = Buffer.concat([buffer, Buffer.isBuffer(chunkArg) ? chunkArg : Buffer.from(chunkArg)]);
      const parsed = parseLgSoundbarFrames(buffer);
      buffer = parsed.rest;
      for (const packet of parsed.packets) {
        received.push(packet);
        const response = lgSoundbarResponseFor(packet);
        if (response) {
          socket.write(encryptLgSoundbarPacket(response));
        }
      }
    });
  });

  await new Promise<void>((resolve, reject) => {
    server.once('error', reject);
    server.listen(0, '127.0.0.1', () => {
      server.off('error', reject);
      resolve();
    });
  });

  const address = server.address();
  if (!address || typeof address === 'string') {
    throw new Error('LG Soundbar test server did not bind to a TCP port.');
  }

  return {
    port: address.port,
    received,
    close: async () => {
      for (const socket of sockets) {
        socket.destroy();
      }
      await new Promise<void>((resolve) => server.close(() => resolve()));
    },
  };
}

function lgSoundbarResponseFor(packetArg: Record<string, unknown>): Record<string, unknown> | undefined {
  if (packetArg.cmd !== 'get') {
    return undefined;
  }
  const responses: Record<string, Record<string, unknown>> = {
    PRODUCT_INFO: { cmd: 'get', msg: 'PRODUCT_INFO', data: { s_model_name: 'SN11RG', s_uuid: 'soundbar-product-uuid' } },
    MAC_INFO_DEV: { cmd: 'get', msg: 'MAC_INFO_DEV', data: { s_uuid: 'soundbar-uuid', s_mac_addr: '00:11:22:33:44:55' } },
    EQ_VIEW_INFO: { cmd: 'get', msg: 'EQ_VIEW_INFO', data: { i_curr_eq: 14, ai_eq_list: [0, 14] } },
    SPK_LIST_VIEW_INFO: { cmd: 'get', msg: 'SPK_LIST_VIEW_INFO', data: { i_vol: 20, i_vol_min: 0, i_vol_max: 40, b_mute: false, i_curr_func: 1, b_powerstatus: true, s_user_name: 'Living Soundbar' } },
    FUNC_VIEW_INFO: { cmd: 'get', msg: 'FUNC_VIEW_INFO', data: { i_curr_func: 1, ai_func_list: [0, 1, 4] } },
    SETTING_VIEW_INFO: { cmd: 'get', msg: 'SETTING_VIEW_INFO', data: { i_curr_eq: 14, s_user_name: 'Living Soundbar' } },
    PLAY_INFO: { cmd: 'get', msg: 'PLAY_INFO', data: { i_stream_type: 1, i_play_ctrl: 0, b_support_play_ctrl: true, s_artist: 'Artist', s_title: 'Track' } },
  };
  return responses[String(packetArg.msg)];
}

const lgSoundbarKey = Buffer.from('T^&*J%^7tr~4^%^&I(o%^!jIJ__+a0 k', 'utf8');
const lgSoundbarIv = Buffer.from("'%^Ur7gy$~t+f)%@", 'utf8');

function encryptLgSoundbarPacket(packetArg: Record<string, unknown>): Buffer<ArrayBufferLike> {
  const cipher = plugins.crypto.createCipheriv('aes-256-cbc', lgSoundbarKey, lgSoundbarIv);
  const encrypted = Buffer.concat([cipher.update(JSON.stringify(packetArg), 'utf8'), cipher.final()]);
  const header = Buffer.alloc(5);
  header[0] = 0x10;
  header.writeUInt32BE(encrypted.length, 1);
  return Buffer.concat([header, encrypted]);
}

function decryptLgSoundbarPacket(dataArg: Buffer<ArrayBufferLike>): Record<string, unknown> {
  const decipher = plugins.crypto.createDecipheriv('aes-256-cbc', lgSoundbarKey, lgSoundbarIv);
  return JSON.parse(Buffer.concat([decipher.update(dataArg), decipher.final()]).toString('utf8')) as Record<string, unknown>;
}

function parseLgSoundbarFrames(bufferArg: Buffer<ArrayBufferLike>): { packets: Record<string, unknown>[]; rest: Buffer<ArrayBufferLike> } {
  const packets: Record<string, unknown>[] = [];
  let offset = 0;
  while (offset < bufferArg.length && bufferArg[offset] !== 0x10) {
    offset++;
  }
  while (bufferArg.length - offset >= 5) {
    const length = bufferArg.readUInt32BE(offset + 1);
    if (bufferArg.length - offset - 5 < length) {
      break;
    }
    packets.push(decryptLgSoundbarPacket(bufferArg.subarray(offset + 5, offset + 5 + length)));
    offset += 5 + length;
  }
  return { packets, rest: bufferArg.subarray(offset) };
}

export default tap.start();
