import { createServer, type IncomingMessage, type ServerResponse } from 'node:http';
import { expect, tap } from '@git.zone/tstest/tapbundle';
import { HomeAssistantOemIntegration, OemClient, OemConfigFlow, OemIntegration, OemMapper, createOemDiscoveryDescriptor, oemProfile, type IOemSnapshot, type TOemRawData } from '../../ts/integrations/oem/index.js';

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');
};

const json = (responseArg: ServerResponse, valueArg: unknown, statusArg = 200): void => {
  responseArg.statusCode = statusArg;
  responseArg.setHeader('content-type', 'application/json');
  responseArg.end(JSON.stringify(valueArg));
};

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

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

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

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

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

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

  expect(snapshot.online).toBeTrue();
  expect(mappedSnapshot.source).toEqual('manual');
  expect(devices[0].integrationDomain).toEqual("oem");
  expect(devices[0].manufacturer).toEqual("OpenEnergyMonitor WiFi Thermostat");
  expect(entities.some((entityArg) => entityArg.integrationDomain === "oem" && entityArg.platform === "climate")).toBeTrue();
});

tap.test('exposes OpenEnergyMonitor WiFi Thermostat runtime, HA alias, and unsupported control without executor', async () => {
  const integration = new OemIntegration();
  const alias = new HomeAssistantOemIntegration();
  expect(alias instanceof OemIntegration).toBeTrue();
  expect(alias.domain).toEqual("oem");
  expect(integration.status).toEqual("control-runtime");
  expect(oemProfile.metadata.configFlow).toEqual(false);
  expect(oemProfile.metadata.requirements).toEqual([
    "oemthermostat==1.1.1",
  ]);

  const runtime = await integration.setup({ name: "OpenEnergyMonitor WiFi Thermostat Runtime", rawData }, {});
  const statusResult = await runtime.callService!({ domain: "oem", service: 'status', target: {} });
  const refresh = await runtime.callService!({ domain: "oem", service: 'refresh', target: {} });
  const snapshot = statusResult.data as IOemSnapshot;

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

  const command = await runtime.callService!({ domain: "oem", service: oemProfile.controlServices?.[0] || 'turn_on', target: {} });
  expect(command.success).toBeFalse();
  expect(command.error!).toContain('requires an injected client.execute() or commandExecutor');
  await runtime.destroy();
});

tap.test('reads and controls OpenEnergyMonitor thermostats over the native HTTP API', async () => {
  const requests: Array<{ method?: string; url?: string; body?: string; authorization?: string }> = [];
  const server = createServer((requestArg: IncomingMessage, responseArg: ServerResponse) => {
    void (async () => {
      const body = requestArg.method === 'POST' ? await readBody(requestArg) : undefined;
      requests.push({ method: requestArg.method, url: requestArg.url, body, authorization: requestArg.headers.authorization });
      const url = new URL(requestArg.url || '/', 'http://127.0.0.1');

      if (requestArg.headers.authorization !== `Basic ${Buffer.from('user:pass').toString('base64')}`) {
        json(responseArg, { error: 'unauthorized' }, 401);
        return;
      }
      if (url.pathname === '/control/thermostat.cgi' && url.searchParams.get('param') === 'state') {
        json(responseArg, { temperature: '21.5', manualsetpoint: '1900', state: 1, relay1state: 1 });
        return;
      }
      if (url.pathname === '/control/thermostat.cgi' && requestArg.method === 'POST') {
        responseArg.statusCode = 200;
        responseArg.end('ok');
        return;
      }
      json(responseArg, { error: 'not found' }, 404);
    })().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 url = `http://127.0.0.1:${port}`;
    const client = new OemClient({ url, username: 'user', password: 'pass', timeoutMs: 1000 });
    const snapshot = await client.getSnapshot(true);
    const temperature = await client.execute({ domain: 'climate', service: 'set_temperature', target: {}, data: { temperature: 20.5 } });
    const hvacMode = await client.execute({ domain: 'climate', service: 'set_hvac_mode', target: {}, data: { hvac_mode: 'heat' } });
    const runtime = await new OemIntegration().setup({ url, username: 'user', password: 'pass', timeoutMs: 1000 }, {});
    const status = await runtime.callService!({ domain: 'oem', service: 'status', target: {} });

    expect(snapshot.source).toEqual('http');
    expect(snapshot.online).toBeTrue();
    expect(snapshot.entities[0].state).toEqual('auto');
    expect(snapshot.entities[0].attributes?.target_temperature).toEqual(19);
    expect(temperature.success).toBeTrue();
    expect(hvacMode.success).toBeTrue();
    expect(status.success).toBeTrue();
    expect(requests.some((requestArg) => requestArg.url === '/control/thermostat.cgi?param=thermostat_manualsetpoint' && requestArg.body === '2050')).toBeTrue();
    expect(requests.some((requestArg) => requestArg.url === '/control/thermostat.cgi?param=thermostat_state' && requestArg.body === '2')).toBeTrue();
    await runtime.destroy();
  } finally {
    await new Promise<void>((resolve, reject) => server.close((errorArg) => errorArg ? reject(errorArg) : resolve()));
  }
});

export default tap.start();
