import { expect, tap } from '@git.zone/tstest/tapbundle';
import { HomeAssistantLibreHardwareMonitorIntegration, LibreHardwareMonitorClient, LibreHardwareMonitorConfigFlow, LibreHardwareMonitorIntegration, LibreHardwareMonitorMapper, createLibreHardwareMonitorDiscoveryDescriptor, libreHardwareMonitorProfile, type ILibreHardwareMonitorSnapshot, type TLibreHardwareMonitorRawData } from '../../ts/integrations/libre_hardware_monitor/index.js';

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

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

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

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

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

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

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

tap.test('polls Libre Hardware Monitor /data.json through native HTTP', async () => {
  const originalFetch = globalThis.fetch;
  const requests: Array<{ url: string; authorization?: string }> = [];

  globalThis.fetch = (async (inputArg: RequestInfo | URL, initArg?: RequestInit) => {
    const headers = initArg?.headers as Record<string, string> | undefined;
    requests.push({ url: String(inputArg), authorization: headers?.authorization });
    return new Response(JSON.stringify(libreHardwareMonitorFixture), { headers: { 'content-type': 'application/json' } });
  }) as typeof globalThis.fetch;

  try {
    const client = new LibreHardwareMonitorClient({ host: '127.0.0.1', port: 8085, username: 'user', password: 'pass' });
    const snapshot = await client.getSnapshot(true);
    const cpuEntity = snapshot.entities.find((entityArg) => entityArg.id === 'amdcpu-0-temperature-0');

    expect(snapshot.source).toEqual('http');
    expect(snapshot.device.name).toEqual('COMPUTER');
    expect(snapshot.entities.length).toEqual(2);
    expect(cpuEntity?.name).toEqual('CPU Package Temperature');
    expect(cpuEntity?.state).toEqual('40.0');
    expect(cpuEntity?.unit).toEqual('C');
    expect(cpuEntity?.attributes?.min_value).toEqual('38.0');
    expect(requests[0].url).toEqual('http://127.0.0.1:8085/data.json');
    expect(requests[0].authorization).toEqual(`Basic ${Buffer.from('user:pass').toString('base64')}`);
  } finally {
    globalThis.fetch = originalFetch;
  }
});

tap.test('exposes Libre Hardware Monitor runtime, HA alias, and unsupported control without executor', async () => {
  const integration = new LibreHardwareMonitorIntegration();
  const alias = new HomeAssistantLibreHardwareMonitorIntegration();
  expect(alias instanceof LibreHardwareMonitorIntegration).toBeTrue();
  expect(alias.domain).toEqual("libre_hardware_monitor");
  expect(integration.status).toEqual("read-only-runtime");
  expect(libreHardwareMonitorProfile.metadata.configFlow).toEqual(true);
  expect(libreHardwareMonitorProfile.metadata.requirements).toEqual([
    "librehardwaremonitor-api==1.11.1",
  ]);

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

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

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

const libreHardwareMonitorFixture = {
  Version: '0.9.7',
  Text: 'Sensor',
  Children: [
    {
      Text: 'COMPUTER',
      ImageURL: 'images_icon/computer.png',
      Children: [
        {
          Text: 'AMD Ryzen',
          HardwareId: '/amdcpu/0',
          ImageURL: 'images_icon/cpu.png',
          Children: [
            {
              Text: 'Temperatures',
              ImageURL: 'images_icon/temperature.png',
              Children: [
                {
                  Text: 'CPU Package',
                  Value: '40,0 C',
                  Min: '38,0 C',
                  Max: '70,0 C',
                  SensorId: '/amdcpu/0/temperature/0',
                  Type: 'Temperature',
                  ImageURL: 'images/transparent.png',
                  Children: [],
                },
              ],
            },
            {
              Text: 'Load',
              ImageURL: 'images_icon/load.png',
              Children: [
                {
                  Text: 'CPU Total',
                  Value: '12,5 %',
                  Min: '0,0 %',
                  Max: '90,0 %',
                  SensorId: '/amdcpu/0/load/0',
                  Type: 'Load',
                  ImageURL: 'images/transparent.png',
                  Children: [],
                },
              ],
            },
          ],
        },
      ],
    },
  ],
};

export default tap.start();
