import { expect, tap } from '@git.zone/tstest/tapbundle';
import { MaryttsClient, MaryttsConfigFlow, MaryttsIntegration, MaryttsMapper, createMaryttsDiscoveryDescriptor, maryttsProfile, type IMaryttsSnapshot, type TMaryttsRawData } from '../../ts/integrations/marytts/index.js';

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

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

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

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

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

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

  expect(snapshot.online).toBeTrue();
  expect(mappedSnapshot.source).toEqual('manual');
  expect(devices[0].integrationDomain).toEqual("marytts");
  expect(devices[0].manufacturer).toEqual("MaryTTS");
  expect(entities.some((entityArg) => entityArg.integrationDomain === "marytts" && entityArg.platform === "sensor")).toBeTrue();
});

tap.test('exposes MaryTTS runtime and unsupported control without executor', async () => {
  const integration = new MaryttsIntegration();
  expect(integration.status).toEqual("control-runtime");
  expect(maryttsProfile.metadata.configFlow).toEqual(false);
  expect(maryttsProfile.metadata.requirements).toEqual([
    "speak2mary==1.4.0",
  ]);

  const runtime = await integration.setup({ name: "MaryTTS Runtime", rawData }, {});
  const statusResult = await runtime.callService!({ domain: "marytts", service: 'status', target: {} });
  const refresh = await runtime.callService!({ domain: "marytts", service: 'refresh', target: {} });
  const snapshot = statusResult.data as IMaryttsSnapshot;

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

  const command = await runtime.callService!({ domain: "marytts", service: maryttsProfile.controlServices?.[0] || 'turn_on', target: {} });
  expect(command.success).toBeFalse();
  expect(command.error!).toContain('MaryTTS speak/get_tts_audio requires data.message');
  await runtime.destroy();
});

export default tap.start();
