import { expect, tap } from '@git.zone/tstest/tapbundle';
import { AquostvClient, AquostvConfigFlow, AquostvIntegration, AquostvMapper, createAquostvDiscoveryDescriptor, type IAquostvSnapshot } from '../../ts/integrations/aquostv/index.js';

const rawData = {
  "power": true,
  "input": "HDMI1",
  "volume": 18
};

tap.test('matches manual Sharp Aquos TV candidates and creates config flow output', async () => {
  const descriptor = createAquostvDiscoveryDescriptor();
  const matcher = descriptor.getMatchers().find((matcherArg) => matcherArg.id === 'aquostv-manual-match');
  const result = await matcher!.matches({ host: 'aquostv.local', name: 'Sharp Aquos TV', metadata: { rawData } }, {});

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

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

  const done = await (await new AquostvConfigFlow().start(result.candidate!, {})).submit!({});
  expect(done.kind).toEqual('done');
  expect(done.config?.host).toEqual('aquostv.local');
});

tap.test('maps Sharp Aquos TV raw snapshots to runtime devices and entities', async () => {
  const client = new AquostvClient({ name: 'Sharp Aquos TV Test', rawData });
  const snapshot = await client.getSnapshot();
  const devices = AquostvMapper.toDevices(snapshot);
  const entities = AquostvMapper.toEntities(snapshot);

  expect(snapshot.online).toBeTrue();
  expect(snapshot.source).toEqual('manual');
  expect(devices[0].integrationDomain).toEqual('aquostv');
  expect(entities.length > 0).toBeTrue();
});

tap.test('exposes Sharp Aquos TV runtime services without fake live control', async () => {
  const runtime = await new AquostvIntegration().setup({ name: 'Sharp Aquos TV Runtime', rawData }, {});
  const status = await runtime.callService!({ domain: 'aquostv', service: 'status', target: {} });
  const snapshot = status.data as IAquostvSnapshot;

  expect(status.success).toBeTrue();
  expect(snapshot.online).toBeTrue();
  expect((await runtime.devices())[0].name).toEqual('Sharp Aquos TV Runtime');

  const liveCommand = await runtime.callService!({ domain: 'aquostv', service: 'turn_on', target: {} });
  expect(liveCommand.success).toBeFalse();
  await runtime.destroy();

  const executorRuntime = await new AquostvIntegration().setup({
    name: 'Sharp Aquos TV Executor',
    rawData,
    commandExecutor: {
      execute: async (requestArg) => ({ success: true, data: { service: requestArg.service } }),
    },
  }, {});
  const executed = await executorRuntime.callService!({ domain: 'aquostv', service: 'turn_on', target: {} });
  expect(executed.success).toBeTrue();
  expect((executed.data as { service: string }).service).toEqual('turn_on');
  await executorRuntime.destroy();
});

export default tap.start();
