import { createServer, type IncomingMessage } from 'node:http';
import { expect, tap } from '@git.zone/tstest/tapbundle';
import { HomeAssistantOctoprintIntegration, OctoprintClient, OctoprintConfigFlow, OctoprintIntegration, OctoprintMapper, createOctoprintDiscoveryDescriptor, octoprintProfile, type IOctoprintSnapshot, type TOctoprintRawData } from '../../ts/integrations/octoprint/index.js';

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

tap.test('reads and controls OctoPrint over the native REST API', async () => {
  const requests: Array<{ method?: string; url?: string; apiKey?: string | string[]; body?: unknown }> = [];
  const server = createServer((requestArg, responseArg) => {
    void (async () => {
      const bodyText = requestArg.method === 'POST' ? await readBody(requestArg) : '';
      requests.push({ method: requestArg.method, url: requestArg.url, apiKey: requestArg.headers['x-api-key'], body: bodyText ? JSON.parse(bodyText) as unknown : undefined });
      if (requestArg.headers['x-api-key'] !== 'octo-key') {
        responseArg.statusCode = 403;
        responseArg.end('forbidden');
        return;
      }
      const path = new URL(requestArg.url || '/', 'http://127.0.0.1').pathname;
      responseArg.setHeader('content-type', 'application/json');
      if (path === '/api/job') {
        if (requestArg.method === 'POST') {
          responseArg.statusCode = 204;
          responseArg.end();
          return;
        }
        responseArg.end(JSON.stringify({ state: 'Printing', progress: { completion: 42.4242, printTime: 120, printTimeLeft: 240 }, job: { file: { name: 'cube.gcode', size: 123456 } } }));
        return;
      }
      if (path === '/api/printer') {
        responseArg.end(JSON.stringify({ state: { text: 'Printing', flags: { printing: true, error: false, paused: false } }, temperature: { tool0: { actual: 201.2, target: 205 }, bed: { actual: 60, target: 65 } } }));
        return;
      }
      if (path === '/api/settings') {
        responseArg.end(JSON.stringify({ plugins: { discovery: { upnpUuid: 'octo-uuid' } }, webcam: { webcamEnabled: true, streamUrl: '/webcam/?action=stream' } }));
        return;
      }
      if (path === '/api/printer/tool' || path === '/api/system/commands/core/reboot' || path === '/api/connection') {
        responseArg.statusCode = 204;
        responseArg.end();
        return;
      }
      responseArg.statusCode = 404;
      responseArg.end(JSON.stringify({ error: 'not found' }));
    })().catch((errorArg) => {
      responseArg.statusCode = 500;
      responseArg.end(String(errorArg));
    });
  });

  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 client = new OctoprintClient({ host: '127.0.0.1', port, apiKey: 'octo-key', timeoutMs: 1000 });
    const snapshot = await client.getSnapshot();
    const pause = await client.execute({ domain: 'octoprint', service: 'press', target: {}, data: { action: 'pause_job' } });
    const temperature = await client.execute({ domain: 'number', service: 'set_value', target: { entityId: 'number.octoprint_tool0_target_temperature' }, data: { value: 215 } });
    const reboot = await client.execute({ domain: 'octoprint', service: 'press', target: {}, data: { action: 'reboot_system' } });

    expect(snapshot.online).toBeTrue();
    expect(snapshot.source).toEqual('http');
    expect(snapshot.device.id).toEqual('octo-uuid');
    expect(snapshot.entities.find((entityArg) => entityArg.id === 'current_state')?.state).toEqual('printing');
    expect(snapshot.entities.find((entityArg) => entityArg.id === 'tool0_actual_temperature')?.state).toEqual(201.2);
    expect(snapshot.entities.find((entityArg) => entityArg.id === 'tool0_target_temperature')?.platform).toEqual('number');
    expect(pause.success).toBeTrue();
    expect(temperature.success).toBeTrue();
    expect(reboot.success).toBeTrue();
    expect(requests.some((requestArg) => requestArg.url === '/api/job' && requestArg.method === 'POST' && (requestArg.body as { command?: string; action?: string }).command === 'pause')).toBeTrue();
    expect(requests.some((requestArg) => requestArg.url === '/api/printer/tool' && JSON.stringify(requestArg.body).includes('tool0'))).toBeTrue();
    expect(requests.some((requestArg) => requestArg.url === '/api/system/commands/core/reboot' && requestArg.method === 'POST')).toBeTrue();
  } finally {
    await new Promise<void>((resolve, reject) => server.close((errorArg) => errorArg ? reject(errorArg) : resolve()));
  }
});

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

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

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

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

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

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

tap.test('exposes OctoPrint runtime, HA alias, and unsupported control without executor', async () => {
  const integration = new OctoprintIntegration();
  const alias = new HomeAssistantOctoprintIntegration();
  expect(alias instanceof OctoprintIntegration).toBeTrue();
  expect(alias.domain).toEqual("octoprint");
  expect(integration.status).toEqual("control-runtime");
  expect(octoprintProfile.metadata.configFlow).toEqual(true);
  expect(octoprintProfile.metadata.requirements).toEqual([
    "pyoctoprintapi==0.1.14",
  ]);

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

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

  const command = await runtime.callService!({ domain: "octoprint", service: octoprintProfile.controlServices?.[0] || 'turn_on', target: {} });
  expect(command.success).toBeFalse();
  expect(command.error!).toContain('Static snapshots/manual data are read-only');
  await runtime.destroy();
});

const readBody = async (requestArg: IncomingMessage): Promise<string> => {
  const chunks: Buffer[] = [];
  for await (const chunk of requestArg) {
    chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
  }
  return Buffer.concat(chunks).toString('utf8');
};

export default tap.start();
