import { expect, tap } from '@git.zone/tstest/tapbundle';
import { LitejetClient, LitejetConfigFlow, LitejetIntegration, LitejetMapper, createLitejetDiscoveryDescriptor, litejetProfile, type ILitejetSnapshot, type TLitejetRawData } from '../../ts/integrations/litejet/index.js';

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

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

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

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

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

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

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

tap.test('exposes LiteJet runtime and unsupported control without executor', async () => {
  const integration = new LitejetIntegration();
  expect(integration.domain).toEqual("litejet");
  expect(integration.status).toEqual("control-runtime");
  expect(litejetProfile.metadata.configFlow).toEqual(true);
  expect(litejetProfile.metadata.requirements).toEqual([
    "pylitejet==0.6.3",
  ]);
  expect((litejetProfile.metadata.localApi as { explicitUnsupported: string[] }).explicitUnsupported.some((itemArg) => itemArg.includes('RS232') && itemArg.includes('no serial-port transport dependency'))).toBeTrue();

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

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

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