import { expect, tap } from '@git.zone/tstest/tapbundle';
import { HomeAssistantIronOsIntegration, IronOsClient, IronOsConfigFlow, IronOsIntegration, IronOsMapper, createIronOsDiscoveryDescriptor, ironOsProfile, type IIronOsSnapshot, type TIronOsRawData } from '../../ts/integrations/iron_os/index.js';

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

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

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

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

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

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

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

tap.test('does not treat arbitrary IronOS 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 IronOsClient({ 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 IronOS runtime, HA alias, and unsupported control without executor', async () => {
  const integration = new IronOsIntegration();
  const alias = new HomeAssistantIronOsIntegration();
  expect(alias instanceof IronOsIntegration).toBeTrue();
  expect(alias.domain).toEqual("iron_os");
  expect(integration.status).toEqual("control-runtime");
  expect(ironOsProfile.metadata.configFlow).toEqual(true);
  expect(ironOsProfile.metadata.requirements).toEqual([
    "pynecil==4.2.1",
  ]);
  expect((ironOsProfile.metadata.localApi as { status: string }).status).toContain('Bluetooth LE/GATT');
  expect((ironOsProfile.metadata.localApi as { explicitUnsupported: string[] }).explicitUnsupported.some((entryArg) => entryArg.includes('bleak/habluetooth'))).toBeTrue();

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

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

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