import { expect, tap } from '@git.zone/tstest/tapbundle';
import { HomeAssistantIperf3Integration, Iperf3Client, Iperf3ConfigFlow, Iperf3Integration, Iperf3Mapper, createIperf3DiscoveryDescriptor, iperf3Profile, type IIperf3Snapshot, type TIperf3RawData } from '../../ts/integrations/iperf3/index.js';

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

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

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

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

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

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

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

tap.test('does not treat arbitrary Iperf3 host/path as a native live API', async () => {
  const originalFetch = globalThis.fetch;
  let fetched = false;
  globalThis.fetch = (async () => {
    fetched = true;
    return new Response('{}');
  }) as typeof globalThis.fetch;

  try {
    const snapshot = await new Iperf3Client({ host: '127.0.0.1', path: '/api', timeoutMs: 1000 }).getSnapshot(true);

    expect(fetched).toBeFalse();
    expect(snapshot.online).toBeFalse();
    expect(snapshot.error!).toContain('snapshots require');
  } finally {
    globalThis.fetch = originalFetch;
  }
});

tap.test('exposes Iperf3 runtime, HA alias, and unsupported control without executor', async () => {
  const integration = new Iperf3Integration();
  const alias = new HomeAssistantIperf3Integration();
  expect(alias instanceof Iperf3Integration).toBeTrue();
  expect(alias.domain).toEqual("iperf3");
  expect(integration.status).toEqual("control-runtime");
  expect(iperf3Profile.metadata.configFlow).toEqual(false);
  expect(iperf3Profile.metadata.requirements).toEqual([
    "iperf3==0.1.11",
  ]);
  expect((iperf3Profile.metadata.localApi as { status: string }).status).toContain('libiperf');
  expect((iperf3Profile.metadata.localApi as { explicitUnsupported: string[] }).explicitUnsupported.some((entryArg) => entryArg.includes('libiperf.so'))).toBeTrue();

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

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

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