import { createServer, type IncomingMessage, type ServerResponse } from 'node:http';
import { expect, tap } from '@git.zone/tstest/tapbundle';
import { HomeAssistantMjpegIntegration, MjpegClient, MjpegConfigFlow, MjpegIntegration, MjpegMapper, createMjpegDiscoveryDescriptor, mjpegProfile, type IMjpegSnapshot, type TMjpegRawData } from '../../ts/integrations/mjpeg/index.js';

const jpegBytes = Buffer.from([0xff, 0xd8, 0xff, 0xd9]);

const rawData: TMjpegRawData = {
  device: {
    id: 'mjpeg-device-1',
    name: "MJPEG IP Camera Device",
    manufacturer: "MJPEG IP Camera",
    model: "MJPEG IP Camera local integration",
    serialNumber: 'mjpeg-serial-1',
  },
  entities: [
    { id: 'camera', name: 'Camera', platform: "camera", state: 'online', attributes: { domain: "mjpeg" } },
  ],
  online: true,
  updatedAt: '2026-01-01T00:00:00.000Z',
  source: 'manual',
};

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

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

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

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

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

  expect(snapshot.online).toBeTrue();
  expect(mappedSnapshot.source).toEqual('manual');
  expect(devices[0].integrationDomain).toEqual("mjpeg");
  expect(devices[0].manufacturer).toEqual("MJPEG IP Camera");
  expect(entities.some((entityArg) => entityArg.integrationDomain === "mjpeg" && entityArg.platform === "camera")).toBeTrue();
});

tap.test('reads MJPEG still images and streams over local HTTP', async () => {
  const requests: string[] = [];
  const server = createServer((requestArg: IncomingMessage, responseArg: ServerResponse) => {
    const url = new URL(requestArg.url || '/', 'http://127.0.0.1');
    requests.push(url.pathname);
    if (url.pathname === '/snapshot') {
      responseArg.statusCode = 200;
      responseArg.setHeader('content-type', 'image/jpeg');
      responseArg.end(jpegBytes);
      return;
    }
    if (url.pathname === '/stream') {
      responseArg.statusCode = 200;
      responseArg.setHeader('content-type', 'multipart/x-mixed-replace; boundary=frame');
      responseArg.end(Buffer.concat([
        Buffer.from('--frame\r\nContent-Type: image/jpeg\r\n\r\n'),
        jpegBytes,
        Buffer.from('\r\n--frame--\r\n'),
      ]));
      return;
    }
    responseArg.statusCode = 404;
    responseArg.end('not found');
  });

  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 baseUrl = `http://127.0.0.1:${port}`;
    const stillClient = new MjpegClient({ name: 'Camera Still', mjpegUrl: `${baseUrl}/stream`, stillImageUrl: `${baseUrl}/snapshot`, timeoutMs: 1000 });
    const streamRuntime = await new MjpegIntegration().setup({ name: 'Camera Stream', mjpegUrl: `${baseUrl}/stream`, timeoutMs: 1000 }, {});
    const stillSnapshot = await stillClient.getSnapshot(true);
    const streamEntities = await streamRuntime.entities();
    const refresh = await streamRuntime.callService!({ domain: 'mjpeg', service: 'refresh', target: {} });

    expect(stillSnapshot.online).toBeTrue();
    expect(stillSnapshot.source).toEqual('http');
    expect(stillSnapshot.entities[0].platform).toEqual('camera');
    expect(stillSnapshot.entities[0].attributes?.imageSource).toEqual('still');
    expect(streamEntities[0].platform).toEqual('camera');
    expect(streamEntities[0].attributes?.imageSource).toEqual('mjpeg');
    expect(refresh.success).toBeTrue();
    expect(requests.includes('/snapshot')).toBeTrue();
    expect(requests.includes('/stream')).toBeTrue();
    await streamRuntime.destroy();
  } finally {
    await new Promise<void>((resolve, reject) => server.close((errorArg) => errorArg ? reject(errorArg) : resolve()));
  }
});

tap.test('exposes MJPEG IP Camera runtime, HA alias, and unsupported control without executor', async () => {
  const integration = new MjpegIntegration();
  const alias = new HomeAssistantMjpegIntegration();
  expect(alias instanceof MjpegIntegration).toBeTrue();
  expect(alias.domain).toEqual("mjpeg");
  expect(integration.status).toEqual("read-only-runtime");
  expect(mjpegProfile.metadata.configFlow).toEqual(true);
  expect(mjpegProfile.metadata.requirements).toEqual([]);

  const runtime = await integration.setup({ name: "MJPEG IP Camera Runtime", rawData }, {});
  const statusResult = await runtime.callService!({ domain: "mjpeg", service: 'status', target: {} });
  const refresh = await runtime.callService!({ domain: "mjpeg", service: 'refresh', target: {} });
  const snapshot = statusResult.data as IMjpegSnapshot;

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

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