import { expect, tap } from '@git.zone/tstest/tapbundle';
import { GuardianClient, GuardianConfigFlow, GuardianIntegration, GuardianMapper, HomeAssistantGuardianIntegration, createGuardianDiscoveryDescriptor, guardianProfile, type IGuardianSnapshot, type TGuardianRawData } from '../../ts/integrations/guardian/index.js';

const rawData: TGuardianRawData = {
  device: {
    id: 'guardian-5410ec688bcf',
    name: 'Guardian Valve Controller 5410EC688BCF',
    manufacturer: 'Elexa',
    model: 'Guardian valve controller',
    serialNumber: '5410EC688BCF',
    host: '192.0.2.77',
    port: 7777,
  },
  entities: [
    { id: 'leak_detected', name: 'Leak Detected', platform: 'binary_sensor', state: false, deviceClass: 'moisture' },
    { id: 'temperature', name: 'Temperature', platform: 'sensor', state: 68.2, unit: 'F', deviceClass: 'temperature' },
    { id: 'average_current', name: 'Average Current', platform: 'sensor', state: 124, unit: 'mA', deviceClass: 'current' },
    { id: 'valve', name: 'Valve', platform: 'switch', state: true, writable: true, attributes: { valveState: 'open', travel_count: 4 } },
    { id: 'onboard_ap', name: 'Onboard Access Point', platform: 'switch', state: false, writable: true, attributes: { connected_clients: 0 } },
    { id: 'reboot', name: 'Reboot', platform: 'button', state: 'idle', writable: true },
  ],
  apis: {
    valve_status: { state: 'open', average_current: 124, travel_count: 4 },
    system_diagnostics: { firmware: '1.2.3', uptime: 720 },
  },
};

tap.test('matches manual Guardian candidates and creates config flow output', async () => {
  const descriptor = createGuardianDiscoveryDescriptor();
  const matcher = descriptor.getMatchers().find((matcherArg) => matcherArg.id === 'guardian-manual-match');
  const result = await matcher!.matches({ source: 'manual', host: '192.0.2.77', name: 'Guardian 5410EC688BCF', metadata: { rawData } }, {});

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

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

  const done = await (await new GuardianConfigFlow().start(result.candidate!, {})).submit!({});
  expect(done.kind).toEqual('done');
  expect(done.config?.host).toEqual('192.0.2.77');
  expect(done.config?.port).toEqual(7777);
  expect(done.config?.rawData).toEqual(rawData);
});

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

  expect(snapshot.online).toBeTrue();
  expect(mappedSnapshot.source).toEqual('manual');
  expect(devices[0].integrationDomain).toEqual('guardian');
  expect(devices[0].manufacturer).toEqual('Elexa');
  expect(entities.some((entityArg) => entityArg.id === 'binary_sensor.guardian_valve_controller_5410ec688bcf_leak_detected')).toBeTrue();
  expect(entities.some((entityArg) => entityArg.id === 'switch.guardian_valve_controller_5410ec688bcf_valve')).toBeTrue();
});

tap.test('exposes Guardian read-only runtime, HA alias, and unsupported control', async () => {
  const integration = new GuardianIntegration();
  const alias = new HomeAssistantGuardianIntegration();
  expect(alias instanceof GuardianIntegration).toBeTrue();
  expect(alias.domain).toEqual('guardian');
  expect(integration.status).toEqual('read-only-runtime');
  expect(guardianProfile.metadata.configFlow).toEqual(true);
  expect(guardianProfile.metadata.qualityScale).toEqual(undefined);
  expect(guardianProfile.metadata.requirements).toEqual(['aioguardian==2026.01.1']);

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

  expect(status.success).toBeTrue();
  expect(refresh.success).toBeTrue();
  expect(snapshot.online).toBeTrue();
  expect((await runtime.devices())[0].name).toEqual('Guardian Valve Controller 5410EC688BCF');

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

export default tap.start();
