import { createServer } from 'node:http';
import { expect, tap } from '@git.zone/tstest/tapbundle';
import { HomeAssistantPalazzettiIntegration, PalazzettiClient, PalazzettiConfigFlow, PalazzettiIntegration, PalazzettiMapper, createPalazzettiDiscoveryDescriptor, palazzettiProfile, type IPalazzettiSnapshot, type TPalazzettiRawData } from '../../ts/integrations/palazzetti/index.js';

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

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

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

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

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

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

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

tap.test('polls and controls Palazzetti over the local sendmsg HTTP API', async () => {
  const commands: string[] = [];
  const properties = {
    MAC: 'AABBCCDDEEFF',
    LABEL: 'Living Room Stove',
    plzbridge: '1.2.3',
    SYSTEM: '2.2.0',
    STOVETYPE: 1,
    FAN2TYPE: 4,
    FAN2MODE: 3,
    PSENSTYPE: 1,
    SPLMIN: 10,
    SPLMAX: 30,
    MAINTPROBE: 0,
    UICONFIG: 0,
  };
  const attributes = {
    LSTATUS: 6,
    STATUS: 2,
    T1: 21.5,
    T2: 0,
    T3: 0,
    T4: 118,
    T5: 0,
    SETP: 22,
    F2L: 3,
    F3L: 1,
    F4L: 2,
    FANLMINMAX: [0, 5, 0, 5, 0, 5],
    PWR: 4,
    PQT: 12,
    PLEVEL: 20,
  };
  const server = createServer((requestArg, responseArg) => {
    const url = new URL(requestArg.url || '/', 'http://127.0.0.1');
    const command = url.searchParams.get('cmd') || '';
    commands.push(command);
    responseArg.setHeader('content-type', 'application/json');
    if (command === 'GET STDT') {
      responseArg.end(JSON.stringify({ SUCCESS: true, DATA: properties }));
      return;
    }
    if (command === 'GET ALLS') {
      responseArg.end(JSON.stringify({ SUCCESS: true, DATA: attributes }));
      return;
    }
    responseArg.end(JSON.stringify({ SUCCESS: true, DATA: {} }));
  });

  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 PalazzettiClient({ host: '127.0.0.1', port, timeoutMs: 1000 });
    const snapshot = await client.getSnapshot();

    expect(snapshot.online).toBeTrue();
    expect(snapshot.source).toEqual('http');
    expect(snapshot.device.name).toEqual('Living Room Stove');
    expect(snapshot.device.serialNumber).toEqual('AABBCCDDEEFF');
    expect(snapshot.entities.find((entityArg) => entityArg.id === 'status')?.state).toEqual('burning');
    expect(snapshot.entities.find((entityArg) => entityArg.id === 'climate')?.platform).toEqual('climate');
    expect(snapshot.entities.find((entityArg) => entityArg.id === 'fan_left_speed')?.state).toEqual(1);

    const temperature = await client.execute({ domain: 'climate', service: 'set_temperature', target: {}, data: { temperature: 23 } });
    const fan = await client.execute({ domain: 'climate', service: 'set_fan_mode', target: {}, data: { fan_mode: 'auto' } });
    const silent = await client.execute({ domain: 'button', service: 'press', target: {} });

    expect(temperature.success).toBeTrue();
    expect(fan.success).toBeTrue();
    expect(silent.success).toBeTrue();
    expect(commands).toContain('SET SETP 23');
    expect(commands).toContain('SET RFAN 7');
    expect(commands).toContain('SET SLNT 1');
  } finally {
    await new Promise<void>((resolve, reject) => server.close((errorArg) => errorArg ? reject(errorArg) : resolve()));
  }
});

tap.test('exposes Palazzetti runtime, HA alias, and unsupported control without executor', async () => {
  const integration = new PalazzettiIntegration();
  const alias = new HomeAssistantPalazzettiIntegration();
  expect(alias instanceof PalazzettiIntegration).toBeTrue();
  expect(alias.domain).toEqual("palazzetti");
  expect(integration.status).toEqual("control-runtime");
  expect(palazzettiProfile.metadata.configFlow).toEqual(true);
  expect(palazzettiProfile.metadata.requirements).toEqual([
    "pypalazzetti==0.1.20",
  ]);

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

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

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