import { expect, tap } from '@git.zone/tstest/tapbundle';
import { HomeAssistantOpendisplayIntegration, OpendisplayClient, OpendisplayConfigFlow, OpendisplayIntegration, OpendisplayMapper, createOpendisplayDiscoveryDescriptor, opendisplayProfile, type IOpendisplaySnapshot, type TOpendisplayRawData } from '../../ts/integrations/opendisplay/index.js';

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

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

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

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

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

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

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

tap.test('exposes OpenDisplay runtime, HA alias, and unsupported control without executor', async () => {
  const integration = new OpendisplayIntegration();
  const alias = new HomeAssistantOpendisplayIntegration();
  expect(alias instanceof OpendisplayIntegration).toBeTrue();
  expect(alias.domain).toEqual("opendisplay");
  expect(integration.status).toEqual("control-runtime");
  expect(opendisplayProfile.metadata.configFlow).toEqual(true);
  expect(opendisplayProfile.metadata.requirements).toEqual([
    "py-opendisplay==5.9.0",
  ]);
  expect(JSON.stringify(opendisplayProfile.metadata.localApi)).toContain('BLE');
  expect(JSON.stringify(opendisplayProfile.metadata.localApi)).toContain('py-opendisplay/Bleak');

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

  expect(statusResult.success).toBeTrue();
  expect(refresh.success).toBeTrue();
  expect(snapshot.online).toBeTrue();
  expect((await runtime.devices())[0].name).toEqual("OpenDisplay Device");

  const command = await runtime.callService!({ domain: "opendisplay", service: opendisplayProfile.controlServices?.[0] || 'turn_on', target: {} });
  expect(command.success).toBeFalse();
  expect(command.error!).toContain('requires an injected client.execute() or commandExecutor');
  await runtime.destroy();
});

export default tap.start();
