import { expect, tap } from '@git.zone/tstest/tapbundle';
import { MediaroomClient, MediaroomConfigFlow, MediaroomIntegration, MediaroomMapper, createMediaroomDiscoveryDescriptor, mediaroomProfile, type IMediaroomSnapshot, type TMediaroomRawData } from '../../ts/integrations/mediaroom/index.js';

const rawData: TMediaroomRawData = {
  device: {
    id: 'mediaroom-device-1',
    name: "Mediaroom Device",
    manufacturer: "Mediaroom",
    model: "Mediaroom local integration",
    serialNumber: 'mediaroom-serial-1',
  },
  entities: [
    { id: 'status', name: 'Status', platform: "media_player", state: true, attributes: { domain: "mediaroom" } },
  ],
  online: true,
  updatedAt: '2026-01-01T00:00:00.000Z',
  source: 'manual',
};

tap.test('matches manual Mediaroom candidates and creates config flow output', async () => {
  const descriptor = createMediaroomDiscoveryDescriptor();
  const matcher = descriptor.getMatchers().find((matcherArg) => matcherArg.id === 'mediaroom-manual-match');
  const result = await matcher!.matches({ source: 'manual', id: 'mediaroom-device-1', name: "Mediaroom Device", metadata: { rawData } }, {});

  expect(result.matched).toBeTrue();
  expect(result.candidate?.integrationDomain).toEqual("mediaroom");

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

  const done = await (await new MediaroomConfigFlow().start(result.candidate!, {})).submit!({});
  expect(done.kind).toEqual('done');
  expect(done.config?.uniqueId).toEqual('mediaroom-device-1');
  expect(done.config?.rawData).toEqual(rawData);
});

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

  expect(snapshot.online).toBeTrue();
  expect(mappedSnapshot.source).toEqual('manual');
  expect(devices[0].integrationDomain).toEqual("mediaroom");
  expect(devices[0].manufacturer).toEqual("Mediaroom");
  expect(entities.some((entityArg) => entityArg.integrationDomain === "mediaroom" && entityArg.platform === "media_player")).toBeTrue();
});

tap.test('exposes Mediaroom runtime and unsupported control without executor', async () => {
  const integration = new MediaroomIntegration();
  expect(integration.status).toEqual("control-runtime");
  expect(mediaroomProfile.metadata.configFlow).toEqual(false);
  expect(mediaroomProfile.metadata.requirements).toEqual([
    "pymediaroom==0.6.5.4",
  ]);

  const runtime = await integration.setup({ name: "Mediaroom Runtime", rawData }, {});
  const statusResult = await runtime.callService!({ domain: "mediaroom", service: 'status', target: {} });
  const refresh = await runtime.callService!({ domain: "mediaroom", service: 'refresh', target: {} });
  const snapshot = statusResult.data as IMediaroomSnapshot;

  expect(statusResult.success).toBeTrue();
  expect(refresh.success).toBeFalse();
  expect(refresh.error!).toContain('Mediaroom refresh requires a TCP endpoint');
  expect(snapshot.online).toBeTrue();
  expect((await runtime.devices())[0].name).toEqual("Mediaroom Device");

  const command = await runtime.callService!({ domain: "mediaroom", service: mediaroomProfile.controlServices?.[0] || 'turn_on', target: {} });
  expect(command.success).toBeFalse();
  expect(command.error!).toContain('Mediaroom TCP commands require config.host/config.url');
  await runtime.destroy();
});

export default tap.start();
