import { expect, tap } from '@git.zone/tstest/tapbundle';
import { HomeAssistantKebaIntegration, KebaClient, KebaConfigFlow, KebaIntegration, KebaMapper, createKebaDiscoveryDescriptor, kebaProfile, type IKebaSnapshot, type TKebaRawData } from '../../ts/integrations/keba/index.js';

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

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

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

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

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

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

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

tap.test('exposes Keba Charging Station runtime, HA alias, and unsupported control without executor', async () => {
  const integration = new KebaIntegration();
  const alias = new HomeAssistantKebaIntegration();
  expect(alias instanceof KebaIntegration).toBeTrue();
  expect(alias.domain).toEqual("keba");
  expect(integration.status).toEqual("control-runtime");
  expect(kebaProfile.metadata.configFlow).toEqual(false);
  expect(kebaProfile.metadata.requirements).toEqual([
    "keba-kecontact==1.3.0",
  ]);
  const localApi = kebaProfile.metadata.localApi as { status: string; explicitUnsupported: string[] };
  expect(localApi.status).toContain('KEBA KeContact UDP');
  expect(localApi.status).toContain('asyncio-dgram');
  expect(localApi.explicitUnsupported.some((entryArg) => entryArg.includes('no HTTP/TCP/TLS/file protocol'))).toBeTrue();

  const runtime = await integration.setup({ name: "Keba Charging Station Runtime", rawData }, {});
  const statusResult = await runtime.callService!({ domain: "keba", service: 'status', target: {} });
  const refresh = await runtime.callService!({ domain: "keba", service: 'refresh', target: {} });
  const snapshot = statusResult.data as IKebaSnapshot;

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

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