import { expect, tap } from '@git.zone/tstest/tapbundle';
import { HassioClient, HassioConfigFlow, HassioIntegration, HassioMapper, HomeAssistantHassioIntegration, createHassioDiscoveryDescriptor, hassioProfile, type IHassioSnapshot, type THassioRawData } from '../../ts/integrations/hassio/index.js';

const rawData: THassioRawData = {
  device: {
    id: 'home-assistant-supervisor',
    name: 'Home Assistant Supervisor',
    manufacturer: 'Home Assistant',
    model: 'Home Assistant Supervisor',
  },
  entities: [
    { id: 'supervisor_version', name: 'Supervisor Version', platform: 'sensor', state: '2026.05.1', attributes: { channel: 'stable', healthy: true, supported: true } },
    { id: 'host_disk_free', name: 'Host Disk Free', platform: 'sensor', state: 128.4, unit: 'GB', deviceClass: 'data_size' },
    { id: 'core_cpu_percent', name: 'Core CPU Percent', platform: 'sensor', state: 8.2, unit: '%' },
    { id: 'core_ssh_state', name: 'Terminal Add-on', platform: 'binary_sensor', state: true, deviceClass: 'running', attributes: { slug: 'core_ssh', version: '9.15.0' } },
    { id: 'core_ssh_switch', name: 'Terminal Add-on Switch', platform: 'switch', state: true, writable: true, attributes: { slug: 'core_ssh' } },
    { id: 'core_update', name: 'Home Assistant Core Update', platform: 'update', state: false, writable: true, attributes: { installed_version: '2026.5.0', latest_version: '2026.5.0' } },
  ],
  supervisor: {
    healthy: true,
    supported: true,
    version: '2026.05.1',
  },
};

tap.test('matches manual Hassio candidates and creates config flow output', async () => {
  const descriptor = createHassioDiscoveryDescriptor();
  const matcher = descriptor.getMatchers().find((matcherArg) => matcherArg.id === 'hassio-manual-match');
  const result = await matcher!.matches({ source: 'manual', id: 'home-assistant-supervisor', name: 'Home Assistant Supervisor', metadata: { rawData } }, {});

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

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

  const done = await (await new HassioConfigFlow().start(result.candidate!, {})).submit!({});
  expect(done.kind).toEqual('done');
  expect(done.config?.name).toEqual('Home Assistant Supervisor');
  expect(done.config?.rawData).toEqual(rawData);
});

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

  expect(snapshot.online).toBeTrue();
  expect(mappedSnapshot.source).toEqual('manual');
  expect(devices[0].integrationDomain).toEqual('hassio');
  expect(devices[0].manufacturer).toEqual('Home Assistant');
  expect(entities.some((entityArg) => entityArg.id === 'sensor.home_assistant_supervisor_supervisor_version')).toBeTrue();
  expect(entities.some((entityArg) => entityArg.id === 'update.home_assistant_supervisor_core_update')).toBeTrue();
});

tap.test('exposes Hassio read-only runtime, HA alias, and unsupported control', async () => {
  const integration = new HassioIntegration();
  const alias = new HomeAssistantHassioIntegration();
  expect(alias instanceof HassioIntegration).toBeTrue();
  expect(alias.domain).toEqual('hassio');
  expect(integration.status).toEqual('read-only-runtime');
  expect(hassioProfile.metadata.configFlow).toEqual(false);
  expect(hassioProfile.metadata.qualityScale).toEqual('internal');
  expect(hassioProfile.metadata.dependencies).toEqual(['http', 'repairs']);
  expect(hassioProfile.metadata.requirements).toEqual(['aiohasupervisor==0.4.3']);

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

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

  const command = await runtime.callService!({ domain: 'hassio', service: 'addon_start', target: {}, data: { addon: 'core_ssh' } });
  expect(command.success).toBeFalse();
  expect(command.error!).toContain('requires an injected client.execute() or commandExecutor');
  await runtime.destroy();
});

export default tap.start();
