import { expect, tap } from '@git.zone/tstest/tapbundle';
import { HomeAssistantLd2410BleIntegration, Ld2410BleClient, Ld2410BleConfigFlow, Ld2410BleIntegration, Ld2410BleMapper, createLd2410BleDiscoveryDescriptor, ld2410BleProfile, type ILd2410BleSnapshot, type TLd2410BleRawData } from '../../ts/integrations/ld2410_ble/index.js';

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

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

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

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

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

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

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

tap.test('exposes LD2410 BLE runtime, HA alias, and unsupported control without executor', async () => {
  const integration = new Ld2410BleIntegration();
  const alias = new HomeAssistantLd2410BleIntegration();
  expect(alias instanceof Ld2410BleIntegration).toBeTrue();
  expect(alias.domain).toEqual("ld2410_ble");
  expect(integration.status).toEqual("read-only-runtime");
  expect(ld2410BleProfile.metadata.configFlow).toEqual(true);
  expect(ld2410BleProfile.metadata.requirements).toEqual([
    "bluetooth-data-tools==1.28.4",
    "ld2410-ble==0.1.1",
  ]);
  const localApi = ld2410BleProfile.metadata.localApi as { status: string; explicitUnsupported: string[] };
  expect(localApi.status).toContain('unavailable BLE stack');
  expect(localApi.explicitUnsupported.some((itemArg) => itemArg.includes('bleak_retry_connector') && itemArg.includes('ld2410-ble'))).toBeTrue();

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

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

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