import { createServer, type IncomingMessage, type ServerResponse } from 'node:http';
import { expect, tap } from '@git.zone/tstest/tapbundle';
import { HomeAssistantOpenhardwaremonitorIntegration, OpenhardwaremonitorClient, OpenhardwaremonitorConfigFlow, OpenhardwaremonitorIntegration, OpenhardwaremonitorMapper, createOpenhardwaremonitorDiscoveryDescriptor, openhardwaremonitorProfile, type IOpenhardwaremonitorSnapshot, type TOpenhardwaremonitorRawData } from '../../ts/integrations/openhardwaremonitor/index.js';

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: TOpenhardwaremonitorRawData = {
  device: {
    id: 'openhardwaremonitor-device-1',
    name: "Open Hardware Monitor Device",
    manufacturer: "Open Hardware Monitor",
    model: "Open Hardware Monitor local integration",
    serialNumber: 'openhardwaremonitor-serial-1',
  },
  entities: [
    { id: 'status', name: 'Status', platform: "sensor", state: true, attributes: { domain: "openhardwaremonitor" } },
  ],
  online: true,
  updatedAt: '2026-01-01T00:00:00.000Z',
  source: 'manual',
};

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

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

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

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

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

  expect(snapshot.online).toBeTrue();
  expect(mappedSnapshot.source).toEqual('manual');
  expect(devices[0].integrationDomain).toEqual("openhardwaremonitor");
  expect(devices[0].manufacturer).toEqual("Open Hardware Monitor");
  expect(entities.some((entityArg) => entityArg.integrationDomain === "openhardwaremonitor" && entityArg.platform === "sensor")).toBeTrue();
});

tap.test('polls Open Hardware Monitor /data.json over native 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 === '/data.json') {
      json(responseArg, openHardwareMonitorFixture);
      return;
    }
    json(responseArg, { error: 'not_found' }, 404);
  });

  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 OpenhardwaremonitorClient({ url, timeoutMs: 1000 });
    const snapshot = await client.getSnapshot(true);
    const runtime = await new OpenhardwaremonitorIntegration().setup({ url, timeoutMs: 1000 }, {});
    const entities = await runtime.entities();
    const cpuPackage = snapshot.entities.find((entityArg) => entityArg.id === 'computer_intel_cpu_temperatures_cpu_package');

    expect(snapshot.online).toBeTrue();
    expect(snapshot.source).toEqual('http');
    expect(snapshot.device.name).toEqual('COMPUTER');
    expect(snapshot.entities.length).toEqual(2);
    expect(cpuPackage?.name).toEqual('COMPUTER Intel CPU Temperatures CPU Package');
    expect(cpuPackage?.state).toEqual('40.0');
    expect(cpuPackage?.unit).toEqual('C');
    expect(cpuPackage?.attributes?.minimal_value).toEqual('38.0');
    expect(entities.some((entityArg) => entityArg.state === '12.5' && entityArg.name === 'COMPUTER Intel CPU Load CPU Total')).toBeTrue();
    expect(requests).toEqual(['/data.json', '/data.json']);
    await runtime.destroy();
  } finally {
    await new Promise<void>((resolve, reject) => server.close((errorArg) => errorArg ? reject(errorArg) : resolve()));
  }
});

tap.test('exposes Open Hardware Monitor runtime, HA alias, and unsupported control without executor', async () => {
  const integration = new OpenhardwaremonitorIntegration();
  const alias = new HomeAssistantOpenhardwaremonitorIntegration();
  expect(alias instanceof OpenhardwaremonitorIntegration).toBeTrue();
  expect(alias.domain).toEqual("openhardwaremonitor");
  expect(integration.status).toEqual("read-only-runtime");
  expect(openhardwaremonitorProfile.metadata.configFlow).toEqual(false);
  expect(openhardwaremonitorProfile.metadata.requirements).toEqual([]);
  expect(openhardwaremonitorProfile.defaultHttpPath).toEqual('/data.json');

  const runtime = await integration.setup({ name: "Open Hardware Monitor Runtime", rawData }, {});
  const statusResult = await runtime.callService!({ domain: "openhardwaremonitor", service: 'status', target: {} });
  const refresh = await runtime.callService!({ domain: "openhardwaremonitor", service: 'refresh', target: {} });
  const snapshot = statusResult.data as IOpenhardwaremonitorSnapshot;

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

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

const openHardwareMonitorFixture = {
  Text: 'Sensor',
  Children: [
    {
      Text: 'COMPUTER',
      Children: [
        {
          Text: 'Intel CPU',
          Children: [
            {
              Text: 'Temperatures',
              Children: [
                {
                  Text: 'CPU Package',
                  Value: '40,0 C',
                  Min: '38,0 C',
                  Max: '70,0 C',
                  Children: [],
                },
              ],
            },
            {
              Text: 'Load',
              Children: [
                {
                  Text: 'CPU Total',
                  Value: '12,5 %',
                  Min: '0,0 %',
                  Max: '90,0 %',
                  Children: [],
                },
              ],
            },
          ],
        },
      ],
    },
  ],
};

export default tap.start();
