import { expect, tap } from '@git.zone/tstest/tapbundle';
import { HomeAssistantHomevoltIntegration, HomevoltClient, HomevoltConfigFlow, HomevoltIntegration, HomevoltMapper, createHomevoltDiscoveryDescriptor, homevoltProfile, type IHomevoltSnapshot, type THomevoltRawData } from '../../ts/integrations/homevolt/index.js';

const rawData: THomevoltRawData = {
  device: {
    id: 'homevolt-ems-1',
    name: 'Homevolt Battery',
    manufacturer: 'Homevolt',
    model: 'Battery system',
    host: 'homevolt.local',
  },
  entities: [
    { id: 'state_of_charge', name: 'State Of Charge', platform: 'sensor', state: 67, unit: '%', deviceClass: 'battery' },
    { id: 'available_charging_power', name: 'Available Charging Power', platform: 'sensor', state: 4200, unit: 'W', deviceClass: 'power' },
    { id: 'energy_imported', name: 'Energy Imported', platform: 'sensor', state: 18.4, unit: 'kWh', deviceClass: 'energy', stateClass: 'total_increasing' },
    { id: 'local_mode', name: 'Local Mode', platform: 'switch', state: true, writable: true, attributes: { entityCategory: 'config' } },
  ],
  uniqueId: 'HV-1234',
};

tap.test('matches manual Homevolt candidates and creates config flow output', async () => {
  const descriptor = createHomevoltDiscoveryDescriptor();
  const matcher = descriptor.getMatchers().find((matcherArg) => matcherArg.id === 'homevolt-manual-match');
  const result = await matcher!.matches({ source: 'manual', id: 'HV-1234', name: 'Homevolt Battery', host: 'homevolt.local', metadata: { rawData } }, {});

  expect(result.matched).toBeTrue();
  expect(result.candidate?.integrationDomain).toEqual('homevolt');

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

  const done = await (await new HomevoltConfigFlow().start(result.candidate!, {})).submit!({});
  expect(done.kind).toEqual('done');
  expect(done.config?.host).toEqual('homevolt.local');
  expect(done.config?.rawData).toEqual(rawData);
});

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

  expect(snapshot.online).toBeTrue();
  expect(mappedSnapshot.source).toEqual('manual');
  expect(devices[0].integrationDomain).toEqual('homevolt');
  expect(devices[0].manufacturer).toEqual('Homevolt');
  expect(entities.some((entityArg) => entityArg.id === 'sensor.homevolt_battery_state_of_charge')).toBeTrue();
  expect(entities.some((entityArg) => entityArg.id === 'switch.homevolt_battery_local_mode')).toBeTrue();
});

tap.test('exposes Homevolt read-only runtime, HA alias, and unsupported control', async () => {
  const integration = new HomevoltIntegration();
  const alias = new HomeAssistantHomevoltIntegration();
  expect(alias instanceof HomevoltIntegration).toBeTrue();
  expect(alias.domain).toEqual('homevolt');
  expect(integration.status).toEqual('read-only-runtime');
  expect(homevoltProfile.metadata.configFlow).toEqual(true);
  expect(homevoltProfile.metadata.qualityScale).toEqual('silver');
  expect(homevoltProfile.metadata.requirements).toEqual(['homevolt==0.5.0']);

  const runtime = await integration.setup({ name: 'Homevolt Runtime', rawData }, {});
  const status = await runtime.callService!({ domain: 'homevolt', service: 'status', target: {} });
  const refresh = await runtime.callService!({ domain: 'homevolt', service: 'refresh', target: {} });
  const snapshot = status.data as IHomevoltSnapshot;

  expect(status.success).toBeTrue();
  expect(refresh.success).toBeTrue();
  expect(snapshot.online).toBeTrue();
  expect((await runtime.devices())[0].name).toEqual('Homevolt Battery');

  const command = await runtime.callService!({ domain: 'switch', service: 'turn_off', target: { entityId: 'switch.homevolt_battery_local_mode' } });
  expect(command.success).toBeFalse();
  expect(command.error!).toContain('requires an injected client.execute() or commandExecutor');
  await runtime.destroy();
});

export default tap.start();
