import { expect, tap } from '@git.zone/tstest/tapbundle';
import { DoodsClient, DoodsConfigFlow, DoodsIntegration, DoodsMapper, HomeAssistantDoodsIntegration, createDoodsDiscoveryDescriptor, doodsProfile, type IDoodsSnapshot } from '../../ts/integrations/doods/index.js';

const rawData = {
  detector: 'default',
  total_matches: 2,
  process_time: 0.13,
  online: true,
};

tap.test('matches manual DOODS candidates and creates config flow output', async () => {
  const descriptor = createDoodsDiscoveryDescriptor();
  const matcher = descriptor.getMatchers().find((matcherArg) => matcherArg.id === 'doods-manual-match');
  const result = await matcher!.matches({ host: 'doods.local', name: 'DOODS - Dedicated Open Object Detection Service', metadata: { rawData, path: '/detect' } }, {});

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

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

  const done = await (await new DoodsConfigFlow().start(result.candidate!, {})).submit!({});
  expect(done.kind).toEqual('done');
  expect(done.config?.host).toEqual('doods.local');
  expect(done.config?.path).toEqual('/detect');
});

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

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

tap.test('exposes DOODS read-only runtime without fake control', async () => {
  expect(new HomeAssistantDoodsIntegration().domain).toEqual('doods');
  expect(doodsProfile.status).toEqual('read-only-runtime');
  expect(doodsProfile.metadata.qualityScale).toEqual('legacy');
  expect(doodsProfile.metadata.requirements).toEqual(['pydoods==1.0.2', 'Pillow==12.2.0']);
  expect(doodsProfile.metadata.configFlow).toBeFalse();

  const runtime = await new DoodsIntegration().setup({ name: 'DOODS Runtime', rawData }, {});
  const status = await runtime.callService!({ domain: 'doods', service: 'status', target: {} });
  const snapshot = status.data as IDoodsSnapshot;

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

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

export default tap.start();
