import { expect, tap } from '@git.zone/tstest/tapbundle';
import { HomeAssistantHorizonIntegration, HorizonClient, HorizonConfigFlow, HorizonIntegration, HorizonMapper, createHorizonDiscoveryDescriptor, horizonProfile, type IHorizonSnapshot, type THorizonRawData } from '../../ts/integrations/horizon/index.js';

const rawData: THorizonRawData = {
  device: {
    id: 'horizon-recorder',
    name: 'Horizon Recorder',
    manufacturer: 'Unitymedia',
    model: 'Horizon HD Recorder',
    host: 'horizon.local',
    port: 5900,
  },
  entities: [
    { id: 'media_player', name: 'Media Player', platform: 'media_player', state: 'playing', writable: true, attributes: { mediaType: 'channel', channel: 101, supportedFeatures: ['turn_on', 'turn_off', 'media_play', 'media_pause'] } },
  ],
};

tap.test('matches manual Horizon candidates and creates config flow output', async () => {
  const descriptor = createHorizonDiscoveryDescriptor();
  const matcher = descriptor.getMatchers().find((matcherArg) => matcherArg.id === 'horizon-manual-match');
  const result = await matcher!.matches({ source: 'manual', id: 'horizon-recorder', name: 'Horizon Recorder', host: 'horizon.local', port: 5900, metadata: { rawData } }, {});

  expect(result.matched).toBeTrue();
  expect(result.candidate?.integrationDomain).toEqual('horizon');

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

  const done = await (await new HorizonConfigFlow().start(result.candidate!, {})).submit!({});
  expect(done.kind).toEqual('done');
  expect(done.config?.host).toEqual('horizon.local');
  expect(done.config?.port).toEqual(5900);
  expect(done.config?.rawData).toEqual(rawData);
});

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

  expect(snapshot.online).toBeTrue();
  expect(mappedSnapshot.source).toEqual('manual');
  expect(devices[0].integrationDomain).toEqual('horizon');
  expect(devices[0].manufacturer).toEqual('Unitymedia');
  expect(entities.some((entityArg) => entityArg.id === 'media_player.horizon_recorder_media_player')).toBeTrue();
  expect(entities.some((entityArg) => entityArg.platform === 'media_player' && entityArg.state === 'playing')).toBeTrue();
});

tap.test('exposes Horizon read-only runtime, HA alias, and unsupported control', async () => {
  const integration = new HorizonIntegration();
  const alias = new HomeAssistantHorizonIntegration();
  expect(alias instanceof HorizonIntegration).toBeTrue();
  expect(alias.domain).toEqual('horizon');
  expect(integration.status).toEqual('read-only-runtime');
  expect(horizonProfile.metadata.configFlow).toEqual(false);
  expect(horizonProfile.metadata.qualityScale).toEqual('legacy');
  expect(horizonProfile.metadata.requirements).toEqual(['horimote==0.4.1']);

  const runtime = await integration.setup({ name: 'Horizon Runtime', rawData }, {});
  const status = await runtime.callService!({ domain: 'horizon', service: 'status', target: {} });
  const refresh = await runtime.callService!({ domain: 'horizon', service: 'refresh', target: {} });
  const snapshot = status.data as IHorizonSnapshot;

  expect(status.success).toBeTrue();
  expect(refresh.success).toBeTrue();
  expect(snapshot.online).toBeTrue();
  expect((await runtime.devices())[0].name).toEqual('Horizon Recorder');

  const command = await runtime.callService!({ domain: 'media_player', service: 'media_play_pause', target: { entityId: 'media_player.horizon_recorder_media_player' } });
  expect(command.success).toBeFalse();
  expect(command.error!).toContain('requires an injected client.execute() or commandExecutor');
  await runtime.destroy();
});

export default tap.start();
