import { expect, tap } from '@git.zone/tstest/tapbundle';
import { HomeAssistantPglabIntegration, PglabClient, PglabConfigFlow, PglabIntegration, PglabMapper, createPglabDiscoveryDescriptor, pglabProfile, type IPglabSnapshot, type TPglabRawData } from '../../ts/integrations/pglab/index.js';

const rawData: TPglabRawData = {
  device: {
    id: 'pglab-device-1',
    name: "PG LAB Electronics Device",
    manufacturer: "PG LAB Electronics",
    model: "PG LAB Electronics local integration",
    serialNumber: 'pglab-serial-1',
  },
  entities: [
    { id: 'status', name: 'Status', platform: "cover", state: true, attributes: { domain: "pglab" } },
  ],
  online: true,
  updatedAt: '2026-01-01T00:00:00.000Z',
  source: 'manual',
};

tap.test('matches manual PG LAB Electronics candidates and creates config flow output', async () => {
  const descriptor = createPglabDiscoveryDescriptor();
  const matcher = descriptor.getMatchers().find((matcherArg) => matcherArg.id === 'pglab-manual-match');
  const result = await matcher!.matches({ source: 'manual', id: 'pglab-device-1', name: "PG LAB Electronics Device", metadata: { rawData } }, {});

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

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

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

tap.test('maps PG LAB Electronics raw snapshots to runtime devices and entities', async () => {
  const client = new PglabClient({ name: "PG LAB Electronics Runtime", rawData });
  const snapshot = await client.getSnapshot();
  const mappedSnapshot = PglabMapper.toSnapshotFromRaw({ name: "PG LAB Electronics Runtime" }, rawData);
  const devices = PglabMapper.toDevices(mappedSnapshot);
  const entities = PglabMapper.toEntities(mappedSnapshot);

  expect(snapshot.online).toBeTrue();
  expect(mappedSnapshot.source).toEqual('manual');
  expect(devices[0].integrationDomain).toEqual("pglab");
  expect(devices[0].manufacturer).toEqual("PG LAB Electronics");
  expect(entities.some((entityArg) => entityArg.integrationDomain === "pglab" && entityArg.platform === "cover")).toBeTrue();
});

tap.test('exposes PG LAB Electronics runtime, HA alias, and unsupported control without executor', async () => {
  const integration = new PglabIntegration();
  const alias = new HomeAssistantPglabIntegration();
  expect(alias instanceof PglabIntegration).toBeTrue();
  expect(alias.domain).toEqual("pglab");
  expect(integration.status).toEqual("control-runtime");
  expect(pglabProfile.metadata.configFlow).toEqual(true);
  expect(pglabProfile.metadata.requirements).toEqual([
    "pypglab==0.0.5",
  ]);
  const localApi = pglabProfile.metadata.localApi as { status: string; explicitUnsupported: string[] };
  expect(localApi.status).toContain('pypglab over the MQTT integration');
  expect(localApi.explicitUnsupported.some((itemArg) => itemArg.includes('MQTT broker semantics'))).toBeTrue();
  expect(localApi.explicitUnsupported.some((itemArg) => itemArg.includes('pglab/discovery/#'))).toBeTrue();

  const runtime = await integration.setup({ name: "PG LAB Electronics Runtime", rawData }, {});
  const statusResult = await runtime.callService!({ domain: "pglab", service: 'status', target: {} });
  const refresh = await runtime.callService!({ domain: "pglab", service: 'refresh', target: {} });
  const snapshot = statusResult.data as IPglabSnapshot;

  expect(statusResult.success).toBeTrue();
  expect(refresh.success).toBeTrue();
  expect(snapshot.online).toBeTrue();
  expect((await runtime.devices())[0].name).toEqual("PG LAB Electronics Device");

  const command = await runtime.callService!({ domain: "pglab", service: pglabProfile.controlServices?.[0] || 'turn_on', target: {} });
  expect(command.success).toBeFalse();
  expect(command.error!).toContain('requires an injected client.execute() or commandExecutor');
  await runtime.destroy();
});

export default tap.start();
