import { expect, tap } from '@git.zone/tstest/tapbundle';
import { LuciClient, LuciConfigFlow, LuciIntegration, LuciMapper, createLuciDiscoveryDescriptor, luciProfile, type ILuciSnapshot, type TLuciRawData } from '../../ts/integrations/luci/index.js';

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

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

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

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

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

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

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

tap.test('exposes OpenWrt (luci) runtime and unsupported control without executor', async () => {
  const integration = new LuciIntegration();
  expect(integration.status).toEqual("read-only-runtime");
  expect(luciProfile.metadata.configFlow).toEqual(false);
  expect(luciProfile.metadata.requirements).toEqual([
    "openwrt-luci-rpc==1.1.17",
  ]);

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

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

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