import { expect, tap } from '@git.zone/tstest/tapbundle';
import * as plugins from '../../ts/plugins.js';
import { LinuxBatteryClient, LinuxBatteryConfigFlow, LinuxBatteryIntegration, LinuxBatteryMapper, createLinuxBatteryDiscoveryDescriptor, linuxBatteryProfile, type ILinuxBatterySnapshot, type TLinuxBatteryRawData } from '../../ts/integrations/linux_battery/index.js';

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

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

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

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

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

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

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

tap.test('polls Linux Battery capacity from local power_supply sysfs files', async () => {
  const rootPath = `/tmp/opencode/linux-battery-test-${Date.now()}-${Math.random().toString(16).slice(2)}`;
  const batteryPath = plugins.path.join(rootPath, 'BAT1');
  await plugins.fs.mkdir(batteryPath, { recursive: true });
  await Promise.all(Object.entries({
    capacity: '87\n',
    status: 'Discharging\n',
    manufacturer: 'Framework\n',
    model_name: 'FRANDBA\n',
    serial_number: 'BAT-SERIAL-1\n',
    energy_now: '39120000\n',
    energy_full: '55000000\n',
    voltage_now: '15432000\n',
  }).map(([fileNameArg, valueArg]) => plugins.fs.writeFile(plugins.path.join(batteryPath, fileNameArg), valueArg)));

  try {
    const client = new LinuxBatteryClient({ name: 'Laptop Battery', sysfsPath: rootPath, battery: 1 });
    const snapshot = await client.getSnapshot();
    const refresh = await client.refresh();

    expect(snapshot.online).toBeTrue();
    expect(snapshot.device.manufacturer).toEqual('Framework');
    expect(snapshot.device.serialNumber).toEqual('BAT-SERIAL-1');
    expect(snapshot.entities[0].state).toEqual(87);
    expect(snapshot.entities[0].attributes?.status).toEqual('Discharging');
    expect(snapshot.entities[0].attributes?.path).toEqual(batteryPath);
    expect(refresh.success).toBeTrue();
  } finally {
    await plugins.fs.rm(rootPath, { recursive: true, force: true });
  }
});

tap.test('exposes Linux Battery runtime and unsupported control without executor', async () => {
  const integration = new LinuxBatteryIntegration();
  expect(integration.domain).toEqual("linux_battery");
  expect(integration.status).toEqual("read-only-runtime");
  expect(linuxBatteryProfile.metadata.configFlow).toEqual(false);
  expect(linuxBatteryProfile.metadata.requirements).toEqual([
    "batinfo==0.4.2",
  ]);

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

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

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