import { expect, tap } from '@git.zone/tstest/tapbundle';
import * as plugins from '../../ts/plugins.js';
import { HomeAssistantMochadIntegration, MochadClient, MochadConfigFlow, MochadIntegration, MochadMapper, createMochadDiscoveryDescriptor, mochadProfile, type IMochadSnapshot, type TMochadRawData } from '../../ts/integrations/mochad/index.js';

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

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

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

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

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

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

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

tap.test('reads configured X10 device status and sends commands through mochad TCP', async () => {
  const commands: string[] = [];
  const server = plugins.net.createServer((socketArg) => {
    socketArg.once('data', (chunkArg) => {
      const command = Buffer.from(chunkArg).toString('utf8').trim();
      commands.push(command);
      if (command === 'getstatus a1') {
        socketArg.write('on\n');
        return;
      }
      if (command === 'pl a1 off') {
        socketArg.write('ok\n');
        return;
      }
      socketArg.write('unknown\n');
    });
  });

  await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve));
  try {
    const address = server.address();
    const port = typeof address === 'object' && address ? address.port : 0;
    const client = new MochadClient({
      host: '127.0.0.1',
      port,
      timeoutMs: 1000,
      devices: [{ address: 'a1', name: 'Kitchen Lamp', platform: 'light', commType: 'pl' }],
    });
    const snapshot = await client.getSnapshot();
    const command = await client.execute({ domain: 'light', service: 'turn_off', target: { entityId: 'light.kitchen_lamp' } });

    expect(snapshot.online).toBeTrue();
    expect(snapshot.entities[0].state).toBeTrue();
    expect(snapshot.entities[0].attributes?.address).toEqual('a1');
    expect(command.success).toBeTrue();
    expect(commands).toEqual(['getstatus a1', 'pl a1 off']);
  } finally {
    await new Promise<void>((resolve, reject) => server.close((errorArg) => errorArg ? reject(errorArg) : resolve()));
  }
});

tap.test('exposes Mochad runtime, HA alias, and unsupported control without executor', async () => {
  const integration = new MochadIntegration();
  const alias = new HomeAssistantMochadIntegration();
  expect(alias instanceof MochadIntegration).toBeTrue();
  expect(alias.domain).toEqual("mochad");
  expect(integration.status).toEqual("control-runtime");
  expect(mochadProfile.metadata.configFlow).toEqual(false);
  expect(mochadProfile.metadata.requirements).toEqual([
    "pymochad==0.2.0",
  ]);

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

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

  const command = await runtime.callService!({ domain: "mochad", service: mochadProfile.controlServices?.[0] || 'turn_on', target: {} });
  expect(command.success).toBeFalse();
  expect(command.error!).toContain('Mochad live commands require config.host');
  await runtime.destroy();
});

export default tap.start();
