import { expect, tap } from '@git.zone/tstest/tapbundle';
import { FrontierSiliconIntegration, type IFrontierSiliconRawCommandRequest, type IFrontierSiliconSnapshot } from '../../ts/integrations/frontier_silicon/index.js';

const snapshot: IFrontierSiliconSnapshot = {
  device: { id: 'radio-uuid', name: 'Kitchen Radio', manufacturer: 'Hama', model: 'DIR3100' },
  player: {
    power: true,
    playState: 'paused',
    volume: 20,
    maxVolume: 40,
    muted: false,
    source: 'Internet Radio',
    mode: { key: '0', id: 'ir', label: 'Internet Radio' },
  },
  modes: [{ key: '0', id: 'ir', label: 'Internet Radio' }, { key: '1', id: 'fm', label: 'FM' }],
  equalisers: [{ key: '0', label: 'Flat' }, { key: '1', label: 'Rock' }],
  presets: [{ key: 0, name: 'BBC 6 Music', type: '1' }, { key: 1, name: 'Jazz Radio', type: '1' }],
  online: true,
  source: 'snapshot',
};

tap.test('routes Frontier Silicon media services through an executor', async () => {
  const commands: IFrontierSiliconRawCommandRequest[] = [];
  const runtime = await new FrontierSiliconIntegration().setup({
    snapshot,
    commandExecutor: {
      execute: async (requestArg) => {
        commands.push(requestArg);
        return { status: 'FS_OK' };
      },
    },
  }, {});

  const play = await runtime.callService!({ domain: 'media_player', service: 'media_play', target: { entityId: 'media_player.kitchen_radio' } });
  const volume = await runtime.callService!({ domain: 'media_player', service: 'volume_set', target: { entityId: 'media_player.kitchen_radio' }, data: { volume_level: 0.35 } });
  const source = await runtime.callService!({ domain: 'media_player', service: 'select_source', target: { entityId: 'media_player.kitchen_radio' }, data: { source: 'FM' } });
  const preset = await runtime.callService!({ domain: 'frontier_silicon', service: 'play_preset', target: { entityId: 'media_player.kitchen_radio' }, data: { preset_number: 2 } });

  expect(play.success).toBeTrue();
  expect(volume.success).toBeTrue();
  expect(source.success).toBeTrue();
  expect(preset.success).toBeTrue();
  expect(commands.map((commandArg) => [commandArg.path, commandArg.params.value])).toEqual([
    ['SET/netRemote.play.control', 1],
    ['SET/netRemote.sys.audio.volume', 14],
    ['SET/netRemote.sys.power', 1],
    ['SET/netRemote.sys.mode', '1'],
    ['SET/netRemote.sys.power', 1],
    ['SET/netRemote.nav.action.selectPreset', 1],
  ]);
});

tap.test('does not report live command success for static snapshots without transport', async () => {
  const runtime = await new FrontierSiliconIntegration().setup({ snapshot }, {});
  const result = await runtime.callService!({ domain: 'media_player', service: 'media_play', target: { entityId: 'media_player.kitchen_radio' } });
  expect(result.success).toBeFalse();
  expect(result.error?.includes('config.host, config.webfsapiUrl, or commandExecutor')).toBeTrue();
});

export default tap.start();
