import { expect, tap } from '@git.zone/tstest/tapbundle';
import { EnphaseEnvoyClient, EnphaseEnvoyConfigFlow, EnphaseEnvoyIntegration, EnphaseEnvoyMapper, HomeAssistantEnphaseEnvoyIntegration, createEnphaseEnvoyDiscoveryDescriptor, enphaseEnvoyProfile, type IEnphaseEnvoySnapshot } from '../../ts/integrations/enphase_envoy/index.js';

const rawData = {
  serialNumber: '122334455667',
  envoyModel: 'IQ Envoy',
  firmware: 'D7.6.175',
  partNumber: '800-00554-r01',
  system_production: {
    watts_now: 420,
    watt_hours_today: 3100,
    watt_hours_lifetime: 9123456,
  },
  system_consumption: {
    watts_now: 275,
    watt_hours_today: 2200,
    watt_hours_lifetime: 8123456,
  },
  inverters: {
    'INV-1': { last_report_watts: 210 },
  },
  encharge_aggregate: {
    state_of_charge: 82,
    reserve_state_of_charge: 30,
  },
  enpower: {
    serial_number: 'ENP-1',
    mains_oper_state: 'closed',
    mains_admin_state: 'closed',
    firmware_version: '7.6.175',
  },
  dry_contact_status: {
    relay1: { status: 'closed', name: 'Load Shed Relay' },
  },
  tariff: {
    storage_settings: {
      charge_from_grid: true,
      reserved_soc: 30,
      mode: 'backup',
    },
  },
};

tap.test('matches manual Enphase Envoy candidates and creates config flow output', async () => {
  const descriptor = createEnphaseEnvoyDiscoveryDescriptor();
  const matcher = descriptor.getMatchers().find((matcherArg) => matcherArg.id === 'enphase_envoy-manual-match');
  const result = await matcher!.matches({ host: 'envoy.local', name: 'Envoy 122334455667', metadata: { rawData } }, {});

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

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

  const done = await (await new EnphaseEnvoyConfigFlow().start(result.candidate!, {})).submit!({ username: 'installer', password: '' });
  expect(done.kind).toEqual('done');
  expect(done.config?.host).toEqual('envoy.local');
  expect(done.config?.path).toEqual('/production.json?details=1');
  expect(done.config?.transport).toEqual('http');
});

tap.test('maps Enphase Envoy raw snapshots to devices and entities', async () => {
  const client = new EnphaseEnvoyClient({ host: 'envoy.local', name: 'Envoy 122334455667', rawData });
  const snapshot = await client.getSnapshot();
  const devices = EnphaseEnvoyMapper.toDevices(snapshot);
  const entities = EnphaseEnvoyMapper.toEntities(snapshot);

  expect(snapshot.online).toBeTrue();
  expect(devices[0].integrationDomain).toEqual('enphase_envoy');
  expect(devices[0].manufacturer).toEqual('Enphase');
  expect(entities.some((entityArg) => entityArg.uniqueId.endsWith('_production') && entityArg.state === 420)).toBeTrue();
  expect(entities.some((entityArg) => entityArg.platform === 'number' && entityArg.name === 'Reserve Battery Level')).toBeTrue();
  expect(entities.some((entityArg) => entityArg.platform === 'select' && entityArg.state === 'backup')).toBeTrue();
  expect(entities.some((entityArg) => entityArg.platform === 'switch' && entityArg.name === 'Grid Enabled')).toBeTrue();
});

tap.test('exposes Enphase Envoy runtime, HA alias, and explicit unsupported control without executor', async () => {
  const integration = new EnphaseEnvoyIntegration();
  const alias = new HomeAssistantEnphaseEnvoyIntegration();
  expect(alias.domain).toEqual('enphase_envoy');
  expect(integration.status).toEqual('control-runtime');
  expect(enphaseEnvoyProfile.metadata.qualityScale).toEqual('platinum');
  expect(enphaseEnvoyProfile.metadata.requirements).toEqual(['pyenphase==2.4.8']);

  const runtime = await integration.setup({ host: 'envoy.local', name: 'Envoy 122334455667', rawData }, {});
  const status = await runtime.callService!({ domain: 'enphase_envoy', service: 'status', target: {} });
  const snapshot = status.data as IEnphaseEnvoySnapshot;

  expect(status.success).toBeTrue();
  expect(snapshot.online).toBeTrue();
  expect((await runtime.devices())[0].name).toEqual('Envoy 122334455667');

  const controlCommand = await runtime.callService!({ domain: 'switch', service: 'turn_on', target: {} });
  expect(controlCommand.success).toBeFalse();
  expect(controlCommand.error?.includes('requires an injected client.execute() or commandExecutor')).toBeTrue();
  await runtime.destroy();
});

export default tap.start();
