import { expect, tap } from '@git.zone/tstest/tapbundle';
import { HomeAssistantInkbirdIntegration, InkbirdClient, InkbirdConfigFlow, InkbirdIntegration, InkbirdMapper, createInkbirdDiscoveryDescriptor, inkbirdProfile, type IInkbirdSnapshot, type TInkbirdRawData } from '../../ts/integrations/inkbird/index.js';

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

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

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

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

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

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

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

tap.test('exposes INKBIRD runtime, HA alias, and unsupported control without executor', async () => {
  const integration = new InkbirdIntegration();
  const alias = new HomeAssistantInkbirdIntegration();
  expect(alias instanceof InkbirdIntegration).toBeTrue();
  expect(alias.domain).toEqual("inkbird");
  expect(integration.status).toEqual("read-only-runtime");
  expect(inkbirdProfile.metadata.configFlow).toEqual(true);
  expect(inkbirdProfile.metadata.requirements).toEqual([
    "inkbird-ble==1.1.1",
  ]);
  expect(((inkbirdProfile.metadata.localApi as { explicitUnsupported: string[] }).explicitUnsupported).join(' ')).toContain('BLE stack');

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

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

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