import { expect, tap } from '@git.zone/tstest/tapbundle';
import { HomeAssistantPingIntegration, PingClient, PingConfigFlow, PingIntegration, PingMapper, createPingDiscoveryDescriptor, pingProfile, type IPingSnapshot, type TPingRawData } from '../../ts/integrations/ping/index.js';

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

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

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

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

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

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

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

tap.test('does not fake Ping ICMP with HTTP or TCP probes', async () => {
  const client = new PingClient({ host: '127.0.0.1', port: 65535, path: '/status', transport: 'tcp', timeoutMs: 50 });
  const snapshot = await client.getSnapshot(true);

  expect(snapshot.online).toBeFalse();
  expect(snapshot.error!).toContain('ICMP');
  expect(JSON.stringify(pingProfile.metadata.localApi)).toContain('icmplib');
});

tap.test('exposes Ping (ICMP) runtime, HA alias, and unsupported control without executor', async () => {
  const integration = new PingIntegration();
  const alias = new HomeAssistantPingIntegration();
  expect(alias instanceof PingIntegration).toBeTrue();
  expect(alias.domain).toEqual("ping");
  expect(integration.status).toEqual("read-only-runtime");
  expect(pingProfile.metadata.configFlow).toEqual(true);
  expect(pingProfile.metadata.requirements).toEqual([
    "icmplib==3.0",
  ]);

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

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

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