import { expect, tap } from '@git.zone/tstest/tapbundle';
import { Enigma2Client, Enigma2ConfigFlow, Enigma2Integration, Enigma2Mapper, HomeAssistantEnigma2Integration, createEnigma2DiscoveryDescriptor, enigma2Profile, type IEnigma2Snapshot } from '../../ts/integrations/enigma2/index.js';

const rawData = {
  about: {
    info: {
      brand: 'Dream Property',
      model: 'DM920',
      ifaces: [{ mac: 'AA:BB:CC:DD:EE:FF' }],
    },
  },
  status: {
    in_standby: false,
    muted: false,
    volume: 35,
    is_recording: true,
    source_list: ['BBC One HD', 'BBC Two HD'],
    currservice: {
      station: 'BBC One HD',
      name: 'News at Six',
      serviceref: '1:0:1:1234:0:0:0:0:0:0:',
      fulldescription: 'Evening news',
      begin: 1715200000,
      end: 1715201800,
    },
  },
};

tap.test('matches manual Enigma2 candidates and creates config flow output', async () => {
  const descriptor = createEnigma2DiscoveryDescriptor();
  const matcher = descriptor.getMatchers().find((matcherArg) => matcherArg.id === 'enigma2-manual-match');
  const result = await matcher!.matches({ host: 'enigma2.local', name: 'Living Room Receiver', metadata: { rawData } }, {});

  expect(result.matched).toBeTrue();
  expect(result.candidate?.integrationDomain).toEqual('enigma2');
  expect(result.candidate?.port).toEqual(80);

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

  const done = await (await new Enigma2ConfigFlow().start(result.candidate!, {})).submit!({ username: 'root', password: 'dreambox' });
  expect(done.kind).toEqual('done');
  expect(done.config?.host).toEqual('enigma2.local');
  expect(done.config?.port).toEqual(80);
  expect(done.config?.username).toEqual('root');
});

tap.test('maps Enigma2 raw snapshots to media player devices and entities', async () => {
  const client = new Enigma2Client({ host: 'enigma2.local', name: 'Living Room Receiver', rawData });
  const snapshot = await client.getSnapshot();
  const devices = Enigma2Mapper.toDevices(snapshot);
  const entities = Enigma2Mapper.toEntities(snapshot);

  expect(snapshot.online).toBeTrue();
  expect(devices[0].integrationDomain).toEqual('enigma2');
  expect(devices[0].manufacturer).toEqual('Dream Property');
  expect(entities.length).toEqual(1);
  expect(entities[0].platform).toEqual('media_player');
  expect(entities[0].state).toEqual('on');
  expect(entities[0].attributes?.volumeLevel).toEqual(0.35);
});

tap.test('exposes Enigma2 runtime, HA alias, and explicit unsupported control without executor', async () => {
  const integration = new Enigma2Integration();
  const alias = new HomeAssistantEnigma2Integration();
  expect(alias.domain).toEqual('enigma2');
  expect(integration.status).toEqual('control-runtime');
  expect(enigma2Profile.metadata.configFlow).toEqual(true);
  expect(enigma2Profile.metadata.requirements).toEqual(['openwebifpy==4.3.1']);

  const runtime = await integration.setup({ host: 'enigma2.local', name: 'Living Room Receiver', rawData }, {});
  const status = await runtime.callService!({ domain: 'enigma2', service: 'status', target: {} });
  const snapshot = status.data as IEnigma2Snapshot;

  expect(status.success).toBeTrue();
  expect(snapshot.online).toBeTrue();
  expect((await runtime.devices())[0].name).toEqual('Living Room Receiver');

  const controlCommand = await runtime.callService!({ domain: 'media_player', service: 'turn_off', target: {} });
  expect(controlCommand.success).toBeFalse();
  expect(controlCommand.error?.includes('requires an injected client.execute() or commandExecutor')).toBeTrue();
  await runtime.destroy();
});

export default tap.start();
