import { expect, tap } from '@git.zone/tstest/tapbundle';
import { HomeAssistantMonopriceIntegration, MonopriceClient, MonopriceConfigFlow, MonopriceIntegration, MonopriceMapper, createMonopriceDiscoveryDescriptor, monopriceProfile, type IMonopriceSnapshot, type TMonopriceRawData } from '../../ts/integrations/monoprice/index.js';

const rawData: TMonopriceRawData = {
  device: {
    id: 'monoprice-device-1',
    name: "Monoprice 6-Zone Amplifier Device",
    manufacturer: "Monoprice 6-Zone Amplifier",
    model: "Monoprice 6-Zone Amplifier local integration",
    serialNumber: 'monoprice-serial-1',
  },
  entities: [
    { id: 'status', name: 'Status', platform: "media_player", state: true, attributes: { domain: "monoprice" } },
  ],
  online: true,
  updatedAt: '2026-01-01T00:00:00.000Z',
  source: 'manual',
};

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

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

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

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

tap.test('maps Monoprice 6-Zone Amplifier raw snapshots to runtime devices and entities', async () => {
  const client = new MonopriceClient({ name: "Monoprice 6-Zone Amplifier Runtime", rawData });
  const snapshot = await client.getSnapshot();
  const mappedSnapshot = MonopriceMapper.toSnapshotFromRaw({ name: "Monoprice 6-Zone Amplifier Runtime" }, rawData);
  const devices = MonopriceMapper.toDevices(mappedSnapshot);
  const entities = MonopriceMapper.toEntities(mappedSnapshot);

  expect(snapshot.online).toBeTrue();
  expect(mappedSnapshot.source).toEqual('manual');
  expect(devices[0].integrationDomain).toEqual("monoprice");
  expect(devices[0].manufacturer).toEqual("Monoprice 6-Zone Amplifier");
  expect(entities.some((entityArg) => entityArg.integrationDomain === "monoprice" && entityArg.platform === "media_player")).toBeTrue();
});

tap.test('exposes Monoprice 6-Zone Amplifier runtime, HA alias, and unsupported control without executor', async () => {
  const integration = new MonopriceIntegration();
  const alias = new HomeAssistantMonopriceIntegration();
  expect(alias instanceof MonopriceIntegration).toBeTrue();
  expect(alias.domain).toEqual("monoprice");
  expect(integration.status).toEqual("control-runtime");
  expect(monopriceProfile.metadata.configFlow).toEqual(true);
  expect(monopriceProfile.metadata.requirements).toEqual([
    "pymonoprice==0.5",
  ]);
  expect((monopriceProfile.metadata.localApi as { explicitUnsupported: string[] }).explicitUnsupported.some((itemArg) => itemArg.includes('pyserial/serial_asyncio') && itemArg.includes('RS-232 serial port'))).toBeTrue();

  const runtime = await integration.setup({ name: "Monoprice 6-Zone Amplifier Runtime", rawData }, {});
  const statusResult = await runtime.callService!({ domain: "monoprice", service: 'status', target: {} });
  const refresh = await runtime.callService!({ domain: "monoprice", service: 'refresh', target: {} });
  const snapshot = statusResult.data as IMonopriceSnapshot;

  expect(statusResult.success).toBeTrue();
  expect(refresh.success).toBeTrue();
  expect(snapshot.online).toBeTrue();
  expect((await runtime.devices())[0].name).toEqual("Monoprice 6-Zone Amplifier Device");

  const command = await runtime.callService!({ domain: "monoprice", service: monopriceProfile.controlServices?.[0] || 'turn_on', target: {} });
  expect(command.success).toBeFalse();
  expect(command.error!).toContain('pyserial/serial_asyncio');
  expect(command.error!).toContain('RS-232 serial port');
  await runtime.destroy();
});

export default tap.start();
