import { expect, tap } from '@git.zone/tstest/tapbundle';
import { HomeAssistantNmapTrackerIntegration, NmapTrackerClient, NmapTrackerConfigFlow, NmapTrackerIntegration, NmapTrackerMapper, createNmapTrackerDiscoveryDescriptor, nmapTrackerProfile, type INmapTrackerSnapshot, type TNmapTrackerRawData } from '../../ts/integrations/nmap_tracker/index.js';

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

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

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

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

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

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

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

tap.test('documents why Nmap Tracker has no native live TCP/HTTP client', async () => {
  const localApi = nmapTrackerProfile.metadata.localApi as { status: string; explicitUnsupported: string[] };

  expect(localApi.status).toContain('netmap/python-nmap');
  expect(localApi.status).toContain('external nmap');
  expect(localApi.explicitUnsupported.some((valueArg) => valueArg.includes('getmac') && valueArg.includes('aiooui'))).toBeTrue();
});

tap.test('exposes Nmap Tracker runtime, HA alias, and unsupported control without executor', async () => {
  const integration = new NmapTrackerIntegration();
  const alias = new HomeAssistantNmapTrackerIntegration();
  expect(alias instanceof NmapTrackerIntegration).toBeTrue();
  expect(alias.domain).toEqual("nmap_tracker");
  expect(integration.status).toEqual("read-only-runtime");
  expect(nmapTrackerProfile.metadata.configFlow).toEqual(true);
  expect(nmapTrackerProfile.metadata.requirements).toEqual([
    "netmap==0.7.0.2",
    "getmac==0.9.5",
    "aiooui==0.1.9",
  ]);

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

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

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