import { expect, tap } from '@git.zone/tstest/tapbundle';
import { GenericClient, GenericConfigFlow, GenericIntegration, GenericMapper, HomeAssistantGenericIntegration, createGenericDiscoveryDescriptor, genericProfile, type IGenericSnapshot, type TGenericRawData } from '../../ts/integrations/generic/index.js';

const rawData: TGenericRawData = {
  name: 'Front Door Camera',
  still_image_url: 'http://camera.local/still.jpg',
  stream_source: 'rtsp://camera.local/live',
  content_type: 'image/jpeg',
  advanced: {
    framerate: 2,
    verify_ssl: true,
    rtsp_transport: 'tcp',
    authentication: 'basic',
  },
};

tap.test('matches manual Generic Camera candidates and creates config flow output', async () => {
  const descriptor = createGenericDiscoveryDescriptor();
  const matcher = descriptor.getMatchers().find((matcherArg) => matcherArg.id === 'generic-manual-match');
  const result = await matcher!.matches({ source: 'manual', id: 'front-camera', name: 'Front Door Camera', metadata: { rawData } }, {});

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

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

  const done = await (await new GenericConfigFlow().start(result.candidate!, {})).submit!({});
  expect(done.kind).toEqual('done');
  expect(done.config?.name).toEqual('Front Door Camera');
  expect(done.config?.rawData).toEqual(rawData);
});

tap.test('maps Generic Camera raw snapshots to runtime devices and entities', async () => {
  const client = new GenericClient({ name: 'Front Door Camera', rawData });
  const snapshot = await client.getSnapshot();
  const mappedSnapshot = GenericMapper.toSnapshotFromRaw({ name: 'Front Door Camera' }, rawData);
  const devices = GenericMapper.toDevices(mappedSnapshot);
  const entities = GenericMapper.toEntities(mappedSnapshot);

  expect(snapshot.online).toBeTrue();
  expect(mappedSnapshot.device.manufacturer).toEqual('Generic');
  expect(devices[0].integrationDomain).toEqual('generic');
  expect(entities.some((entityArg) => entityArg.id === 'sensor.front_door_camera_camera')).toBeTrue();
  expect(entities[0].attributes?.streamSource).toEqual('rtsp://camera.local/live');
});

tap.test('exposes Generic Camera read-only runtime, HA alias, and unsupported control', async () => {
  const integration = new GenericIntegration();
  const alias = new HomeAssistantGenericIntegration();
  expect(alias instanceof GenericIntegration).toBeTrue();
  expect(alias.domain).toEqual('generic');
  expect(integration.status).toEqual('read-only-runtime');
  expect(genericProfile.metadata.configFlow).toEqual(true);
  expect(genericProfile.metadata.iotClass).toEqual('local_push');
  expect(genericProfile.metadata.dependencies).toEqual(['http', 'stream']);

  const runtime = await integration.setup({ name: 'Front Door Camera', rawData }, {});
  const status = await runtime.callService!({ domain: 'generic', service: 'status', target: {} });
  const refresh = await runtime.callService!({ domain: 'generic', service: 'refresh', target: {} });
  const snapshot = status.data as IGenericSnapshot;

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

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

export default tap.start();
