import { expect, tap } from '@git.zone/tstest/tapbundle';
import { HomeAssistantLannouncerIntegration, LannouncerClient, LannouncerConfigFlow, LannouncerIntegration, LannouncerMapper, createLannouncerDiscoveryDescriptor, lannouncerProfile, type ILannouncerSnapshot, type TLannouncerRawData } from '../../ts/integrations/lannouncer/index.js';

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

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

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

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

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

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

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

tap.test('exposes LANnouncer runtime, HA alias, and unsupported control without executor', async () => {
  const integration = new LannouncerIntegration();
  const alias = new HomeAssistantLannouncerIntegration();
  expect(alias instanceof LannouncerIntegration).toBeTrue();
  expect(alias.domain).toEqual("lannouncer");
  expect(integration.status).toEqual("read-only-runtime");
  expect(lannouncerProfile.metadata.configFlow).toEqual(false);
  expect(lannouncerProfile.metadata.requirements).toEqual([]);
  const localApi = lannouncerProfile.metadata.localApi as { status: string; explicitUnsupported: string[] };
  expect(localApi.status).toContain('no native live client');
  expect(localApi.explicitUnsupported.some((itemArg) => itemArg.includes('integration_removed repair issue'))).toBeTrue();

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

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

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