import { expect, tap } from '@git.zone/tstest/tapbundle';
import { LacrosseClient, LacrosseConfigFlow, LacrosseIntegration, LacrosseMapper, createLacrosseDiscoveryDescriptor, lacrosseProfile, type ILacrosseSnapshot, type TLacrosseRawData } from '../../ts/integrations/lacrosse/index.js';

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

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

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

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

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

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

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

tap.test('exposes LaCrosse runtime and unsupported control without executor', async () => {
  const integration = new LacrosseIntegration();
  expect(integration.status).toEqual("read-only-runtime");
  expect(lacrosseProfile.metadata.configFlow).toEqual(false);
  expect(lacrosseProfile.metadata.requirements).toEqual([
    "pylacrosse==0.4",
  ]);
  expect(JSON.stringify(lacrosseProfile.metadata.localApi)).toContain('pyserial');
  expect(JSON.stringify(lacrosseProfile.metadata.localApi)).toContain('RFC2217');

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

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

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