import { createServer } from 'node:http';
import { expect, tap } from '@git.zone/tstest/tapbundle';
import { KioskerClient, KioskerConfigFlow, KioskerIntegration, KioskerMapper, createKioskerDiscoveryDescriptor, kioskerProfile, type IKioskerSnapshot, type TKioskerRawData } from '../../ts/integrations/kiosker/index.js';

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

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

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

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

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

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

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

tap.test('polls the documented Kiosker HTTP API and maps Home Assistant entities', async () => {
  const requests: string[] = [];
  const server = createServer((requestArg, responseArg) => {
    requests.push(`${requestArg.method} ${requestArg.url} ${requestArg.headers.authorization}`);
    if (requestArg.headers.authorization !== 'Bearer test-token') {
      responseArg.writeHead(401, { 'content-type': 'application/json' });
      responseArg.end(JSON.stringify({ error: true, reason: 'unauthorized' }));
      return;
    }

    responseArg.writeHead(200, { 'content-type': 'application/json' });
    if (requestArg.url === '/api/v1/status') {
      responseArg.end(JSON.stringify({
        status: {
          batteryLevel: 87,
          batteryState: 'Charging',
          model: 'iPad13,4',
          osVersion: '17.5',
          appName: 'Kiosker Pro',
          appVersion: '25.1.0',
          lastInteraction: '2026-01-01T00:00:00+00:00',
          lastMotion: null,
          ambientLight: 12.5,
          date: '2026-01-01T00:00:05+00:00',
          deviceId: '2904C1F2-93FB-4954-BF85-FAAEFBA814F6',
        },
      }));
      return;
    }
    if (requestArg.url === '/api/v1/blackout/state') {
      responseArg.end(JSON.stringify({ blackout: { visible: true, text: 'Maintenance' } }));
      return;
    }
    if (requestArg.url === '/api/v1/screensaver/state') {
      responseArg.end(JSON.stringify({ screensaver: { visible: false, disabled: false } }));
      return;
    }
    responseArg.end(JSON.stringify({}));
  });
  await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve));

  try {
    const address = server.address();
    const port = typeof address === 'object' && address ? address.port : 0;
    const config = { host: '127.0.0.1', port, token: 'test-token', name: 'Lobby Kiosk', timeoutMs: 1000 };
    const client = new KioskerClient(config);
    const snapshot = await client.getSnapshot(true);
    const entities = KioskerMapper.toEntities(snapshot);

    expect(snapshot.online).toBeTrue();
    expect(snapshot.source).toEqual('http');
    expect(snapshot.device.serialNumber).toEqual('2904C1F2-93FB-4954-BF85-FAAEFBA814F6');
    expect(entities.find((entityArg) => entityArg.uniqueId.endsWith('_batterylevel'))?.state).toEqual(87);
    expect(entities.find((entityArg) => entityArg.uniqueId.endsWith('_blackoutstate'))?.state).toBeTrue();
    expect(entities.find((entityArg) => entityArg.uniqueId.endsWith('_charging'))?.state).toBeTrue();
    expect([...requests].sort()).toEqual([
      'GET /api/v1/blackout/state Bearer test-token',
      'GET /api/v1/screensaver/state Bearer test-token',
      'GET /api/v1/status Bearer test-token',
    ].sort());

    const runtime = await new KioskerIntegration().setup(config, {});
    const status = await runtime.callService!({ domain: 'kiosker', service: 'status', target: {} });
    expect(status.success).toBeTrue();
    expect((status.data as IKioskerSnapshot).source).toEqual('http');
    await runtime.destroy();
  } finally {
    await new Promise<void>((resolve, reject) => server.close((errorArg) => errorArg ? reject(errorArg) : resolve()));
  }
});

tap.test('exposes Kiosker runtime and unsupported control without executor', async () => {
  const integration = new KioskerIntegration();
  expect(integration.status).toEqual("read-only-runtime");
  expect(kioskerProfile.metadata.configFlow).toEqual(true);
  expect(kioskerProfile.metadata.requirements).toEqual([
    "kiosker-python-api==1.2.9",
  ]);
  expect((kioskerProfile.metadata.localApi as { implemented: string[] }).implemented.some((itemArg) => itemArg.includes('/api/v1/status'))).toBeTrue();

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

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

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