import { expect, tap } from '@git.zone/tstest/tapbundle';
import { HomeAssistantPicottsIntegration, PicottsClient, PicottsConfigFlow, PicottsIntegration, PicottsMapper, createPicottsDiscoveryDescriptor, picottsProfile, type IPicottsSnapshot, type TPicottsRawData } from '../../ts/integrations/picotts/index.js';

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

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

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

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

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

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

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

tap.test('does not fake Pico TTS live synthesis without pico2wave subprocess support', async () => {
  const client = new PicottsClient({ host: '127.0.0.1', port: 65535, path: '/tts', timeoutMs: 50 });
  const snapshot = await client.getSnapshot(true);

  expect(snapshot.online).toBeFalse();
  expect(snapshot.error!).toContain('pico2wave');
  expect(JSON.stringify(picottsProfile.metadata.localApi)).toContain('pico2wave');
});

tap.test('exposes Pico TTS runtime, HA alias, and unsupported control without executor', async () => {
  const integration = new PicottsIntegration();
  const alias = new HomeAssistantPicottsIntegration();
  expect(alias instanceof PicottsIntegration).toBeTrue();
  expect(alias.domain).toEqual("picotts");
  expect(integration.status).toEqual("read-only-runtime");
  expect(picottsProfile.metadata.configFlow).toEqual(true);
  expect(picottsProfile.metadata.requirements).toEqual([]);

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

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

  const command = await runtime.callService!({ domain: "picotts", service: picottsProfile.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();
