import { expect, tap } from '@git.zone/tstest/tapbundle';
import { MadvrIntegration, type IMadvrCommandRequest, type IMadvrSnapshot } from '../../ts/integrations/madvr/index.js';

const snapshot: IMadvrSnapshot = {
  deviceInfo: { name: 'Cinema Envy', macAddress: 'AA:BB:CC:DD:EE:FF' },
  processor: { isOn: true, isSignal: true },
  display: {},
  buttons: [{ key: 'hotplug', name: 'Hotplug', command: 'Hotplug' }],
  selects: [{
    key: 'display_profile',
    name: 'Display profile',
    current: 'Cinema',
    options: ['Cinema', 'TV'],
    commands: {
      Cinema: { command: 'ActivateProfile', args: ['DISPLAY', '1'] },
      TV: { command: 'ActivateProfile', args: ['DISPLAY', '2'] },
    },
  }],
  available: true,
};

tap.test('executes modeled madVR commands through an explicit executor', async () => {
  const executed: IMadvrCommandRequest[] = [];
  const integration = new MadvrIntegration();
  const runtime = await integration.setup({
    snapshot,
    commandExecutor: {
      execute: async (commandArg) => {
        executed.push(commandArg);
      },
    },
  }, {});

  const remoteResult = await runtime.callService!({
    domain: 'remote',
    service: 'send_command',
    target: { entityId: 'media_player.cinema_envy' },
    data: { command: 'KeyPress, MENU' },
  });
  expect(remoteResult.success).toBeTrue();
  expect(executed[0].command).toEqual('KeyPress');
  expect(executed[0].args).toEqual(['MENU']);

  const buttonResult = await runtime.callService!({
    domain: 'button',
    service: 'press',
    target: { entityId: 'button.cinema_envy_hotplug' },
  });
  expect(buttonResult.success).toBeTrue();
  expect(executed[1].command).toEqual('Hotplug');

  const selectResult = await runtime.callService!({
    domain: 'select',
    service: 'select_option',
    target: { entityId: 'select.cinema_envy_display_profile' },
    data: { option: 'TV' },
  });
  expect(selectResult.success).toBeTrue();
  expect(executed[2].command).toEqual('ActivateProfile');
  expect(executed[2].args).toEqual(['DISPLAY', '2']);
});

tap.test('runtime reports live command errors instead of pretending success', async () => {
  const integration = new MadvrIntegration();
  const runtime = await integration.setup({ snapshot }, {});
  const result = await runtime.callService!({
    domain: 'remote',
    service: 'turn_off',
    target: { entityId: 'media_player.cinema_envy' },
  });

  expect(result.success).toBeFalse();
  expect(result.error).toContain('host is required');
});

export default tap.start();
