import { expect, tap } from '@git.zone/tstest/tapbundle';
import { DunehdClient, DunehdIntegration, type IDunehdRawCommandRequest, type IDunehdSnapshot } from '../../ts/integrations/dunehd/index.js';

const snapshot: IDunehdSnapshot = {
  deviceInfo: { id: 'dune-123', host: '192.168.1.70', name: 'Living Room Dune' },
  state: { player_state: 'navigator', playback_volume: '40', playback_mute: '0' },
  online: true,
};

tap.test('models Dune HD media and remote commands through an executor', async () => {
  const commands: IDunehdRawCommandRequest[] = [];
  const runtime = await new DunehdIntegration().setup({
    snapshot,
    commandExecutor: {
      execute: async (requestArg) => {
        commands.push(requestArg);
        return { player_state: 'playing', playback_speed: '256' };
      },
    },
  }, {});

  const play = await runtime.callService!({ domain: 'media_player', service: 'media_play', target: { entityId: 'media_player.living_room_dune' } });
  const mute = await runtime.callService!({ domain: 'media_player', service: 'volume_mute', target: { entityId: 'media_player.living_room_dune' }, data: { is_volume_muted: true } });
  const media = await runtime.callService!({ domain: 'media_player', service: 'play_media', target: { entityId: 'media_player.living_room_dune' }, data: { media_content_id: 'http://media.example/movie.mkv' } });
  const remote = await runtime.callService!({ domain: 'remote', service: 'send_command', target: { entityId: 'remote.living_room_dune' }, data: { command: 'previous' } });

  expect(play.success).toBeTrue();
  expect(mute.success).toBeTrue();
  expect(media.success).toBeTrue();
  expect(remote.success).toBeTrue();
  expect(commands.map((commandArg) => commandArg.cmd)).toEqual([
    'set_playback_state',
    'set_playback_state',
    'launch_media_url',
    'ir_code',
  ]);
  expect(commands[0].params.speed).toEqual(256);
  expect(commands[1].params.mute).toEqual(1);
  expect(commands[2].params.media_url).toEqual('http://media.example/movie.mkv');
  expect(commands[3].params.ir_code).toEqual('B649BF00');
});

tap.test('parses Dune HD status name/value payloads', async () => {
  const client = new DunehdClient({});
  const state = client.parseStatus(`
    <param name="player_state" value="navigator"/>
    name="playback_volume" value="55"
  `);

  expect(state.player_state).toEqual('navigator');
  expect(state.playback_volume).toEqual('55');
});

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

export default tap.start();
