import { expect, tap } from '@git.zone/tstest/tapbundle';
import { HomeAssistantOwntracksIntegration, OwntracksClient, OwntracksConfigFlow, OwntracksIntegration, OwntracksMapper, createOwntracksDiscoveryDescriptor, owntracksProfile, type IOwntracksSnapshot, type TOwntracksRawData } from '../../ts/integrations/owntracks/index.js';

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

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

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

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

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

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

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

tap.test('exposes OwnTracks runtime, HA alias, and unsupported control without executor', async () => {
  const integration = new OwntracksIntegration();
  const alias = new HomeAssistantOwntracksIntegration();
  expect(alias instanceof OwntracksIntegration).toBeTrue();
  expect(alias.domain).toEqual("owntracks");
  expect(integration.status).toEqual("read-only-runtime");
  expect(owntracksProfile.metadata.configFlow).toEqual(true);
  expect(owntracksProfile.metadata.requirements).toEqual([
    "PyNaCl==1.6.2",
  ]);

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

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

  const command = await runtime.callService!({ domain: "owntracks", service: owntracksProfile.controlServices?.[0] || 'turn_on', target: {} });
  expect(command.success).toBeFalse();
  expect(command.error!).toContain('requires an injected client.execute() or commandExecutor');
  await runtime.destroy();
});

tap.test('documents OwnTracks push-only blockers and refuses fake HTTP polling', async () => {
  const localApi = owntracksProfile.metadata.localApi as { implemented: string[]; explicitUnsupported: string[] };
  const client = new OwntracksClient({ url: 'http://127.0.0.1:8123/api/webhook/owntracks' });
  const snapshot = await client.getSnapshot(true);

  expect(snapshot.online).toBeFalse();
  expect(snapshot.error!).toContain('push-only');
  expect(localApi.explicitUnsupported.some((itemArg) => itemArg.includes('MQTT broker'))).toBeTrue();
  expect(localApi.explicitUnsupported.some((itemArg) => itemArg.includes('PyNaCl'))).toBeTrue();
  expect(localApi.explicitUnsupported.some((itemArg) => itemArg.includes('webhook'))).toBeTrue();
});

export default tap.start();
