import { expect, tap } from '@git.zone/tstest/tapbundle';
import { HomeAssistantOppleIntegration, OppleClient, OppleConfigFlow, OppleIntegration, OppleMapper, createOppleDiscoveryDescriptor, oppleProfile, type IOppleSnapshot, type TOppleRawData } from '../../ts/integrations/opple/index.js';

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

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

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

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

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

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

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

tap.test('exposes Opple runtime, HA alias, and unsupported control without executor', async () => {
  const integration = new OppleIntegration();
  const alias = new HomeAssistantOppleIntegration();
  expect(alias instanceof OppleIntegration).toBeTrue();
  expect(alias.domain).toEqual("opple");
  expect(integration.status).toEqual("control-runtime");
  expect(oppleProfile.metadata.configFlow).toEqual(false);
  expect(oppleProfile.metadata.requirements).toEqual([
    "pyoppleio-legacy==1.0.8",
  ]);
  const localApi = oppleProfile.metadata.localApi as { status: string; explicitUnsupported: string[] };
  const runtimeMetadata = oppleProfile.metadata.runtime as { blocker: string };
  expect(localApi.status).toEqual('blocked-udp-only-undocumented-binary-protocol');
  expect(runtimeMetadata.blocker).toContain('UDP-only');
  expect(localApi.explicitUnsupported.some((itemArg) => itemArg.includes('socket.SOCK_DGRAM') && itemArg.includes('UDP'))).toBeTrue();
  expect(localApi.explicitUnsupported.some((itemArg) => itemArg.includes('CRC16') && itemArg.includes('encrypted'))).toBeTrue();

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

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

  const command = await runtime.callService!({ domain: "opple", service: oppleProfile.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();
