import { createServer, type IncomingMessage, type ServerResponse } from 'node:http';
import { expect, tap } from '@git.zone/tstest/tapbundle';
import { HomeAssistantMoehlenhoffAlpha2Integration, MoehlenhoffAlpha2Client, MoehlenhoffAlpha2ConfigFlow, MoehlenhoffAlpha2Integration, MoehlenhoffAlpha2Mapper, createMoehlenhoffAlpha2DiscoveryDescriptor, moehlenhoffAlpha2Profile, type IMoehlenhoffAlpha2Snapshot, type TMoehlenhoffAlpha2RawData } from '../../ts/integrations/moehlenhoff_alpha2/index.js';

const xml = (responseArg: ServerResponse, valueArg: string, statusArg = 200): void => {
  responseArg.statusCode = statusArg;
  responseArg.setHeader('content-type', 'application/xml');
  responseArg.end(valueArg);
};

const requestBody = async (requestArg: IncomingMessage): Promise<string> => new Promise((resolve, reject) => {
  const chunks: Buffer[] = [];
  requestArg.on('data', (chunkArg) => chunks.push(Buffer.isBuffer(chunkArg) ? chunkArg : Buffer.from(chunkArg)));
  requestArg.on('end', () => resolve(Buffer.concat(chunks).toString('utf8')));
  requestArg.on('error', reject);
});

const staticXml = (coolingArg = 0): string => `<?xml version="1.0" encoding="UTF-8"?>
<Devices>
  <Device>
    <ID>EZR012345</ID>
    <NAME>Alpha Base</NAME>
    <COOLING>${coolingArg}</COOLING>
    <HEATAREA nr="1">
      <HEATAREA_NAME>Living Room</HEATAREA_NAME>
      <HEATAREA_MODE>1</HEATAREA_MODE>
      <T_ACTUAL>20.2</T_ACTUAL>
      <T_TARGET>21.0</T_TARGET>
      <T_TARGET_MIN>5.0</T_TARGET_MIN>
      <T_TARGET_MAX>30.0</T_TARGET_MAX>
      <T_HEAT_DAY>21.0</T_HEAT_DAY>
      <T_HEAT_NIGHT>18.0</T_HEAT_NIGHT>
      <T_COOL_DAY>23.0</T_COOL_DAY>
      <T_COOL_NIGHT>25.0</T_COOL_NIGHT>
    </HEATAREA>
    <HEATCTRL nr="1">
      <INUSE>1</INUSE>
      <HEATAREA_NR>1</HEATAREA_NR>
      <ACTOR_PERCENT>33</ACTOR_PERCENT>
      <HEATCTRL_STATE>1</HEATCTRL_STATE>
    </HEATCTRL>
    <IODEVICE nr="1">
      <HEATAREA_NR>1</HEATAREA_NR>
      <BATTERY>1</BATTERY>
      <SIGNALSTRENGTH>88</SIGNALSTRENGTH>
      <ISON>1</ISON>
    </IODEVICE>
  </Device>
</Devices>`;

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

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

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

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

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

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

  expect(snapshot.online).toBeTrue();
  expect(mappedSnapshot.source).toEqual('manual');
  expect(devices[0].integrationDomain).toEqual("moehlenhoff_alpha2");
  expect(devices[0].manufacturer).toEqual("Mohlenhoff Alpha 2");
  expect(entities.some((entityArg) => entityArg.integrationDomain === "moehlenhoff_alpha2" && entityArg.platform === "binary_sensor")).toBeTrue();
});

tap.test('polls and controls Mohlenhoff Alpha 2 through the documented local XML HTTP API', async () => {
  const requests: Array<{ method?: string; url?: string; body?: string }> = [];
  let cooling = 0;
  const server = createServer((requestArg: IncomingMessage, responseArg: ServerResponse) => {
    void (async () => {
      if (requestArg.url === '/data/static.xml' && requestArg.method === 'GET') {
        requests.push({ method: requestArg.method, url: requestArg.url });
        xml(responseArg, staticXml(cooling));
        return;
      }
      if (requestArg.url === '/data/changes.xml' && requestArg.method === 'POST') {
        const body = await requestBody(requestArg);
        requests.push({ method: requestArg.method, url: requestArg.url, body });
        if (body.includes('<COOLING>1</COOLING>')) {
          cooling = 1;
        }
        xml(responseArg, '<ok/>');
        return;
      }
      xml(responseArg, '<error/>', 404);
    })().catch((errorArg) => xml(responseArg, `<error>${String(errorArg)}</error>`, 500));
  });

  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 url = `http://127.0.0.1:${port}`;
    const client = new MoehlenhoffAlpha2Client({ url, timeoutMs: 1000 });
    const snapshot = await client.getSnapshot(true);
    const temperature = await client.execute({ domain: 'climate', service: 'set_temperature', target: {}, data: { heatAreaId: 'EZR012345:1', temperature: 21.4 } });
    const hvacMode = await client.execute({ domain: 'climate', service: 'set_hvac_mode', target: {}, data: { hvac_mode: 'cool' } });
    const syncTime = await client.execute({ domain: 'button', service: 'press', target: {}, data: { datetime: '2026-01-01T01:02:03' } });
    const runtime = await new MoehlenhoffAlpha2Integration().setup({ url, timeoutMs: 1000 }, {});
    const entities = await runtime.entities();

    expect(snapshot.online).toBeTrue();
    expect(snapshot.source).toEqual('http');
    expect(snapshot.device.id).toEqual('EZR012345');
    expect(snapshot.entities.some((entityArg) => entityArg.platform === 'climate' && entityArg.state === 21)).toBeTrue();
    expect(snapshot.entities.some((entityArg) => entityArg.platform === 'sensor' && entityArg.state === 33)).toBeTrue();
    expect(snapshot.entities.some((entityArg) => entityArg.platform === 'binary_sensor' && entityArg.state === true)).toBeTrue();
    expect(temperature.success).toBeTrue();
    expect(hvacMode.success).toBeTrue();
    expect(syncTime.success).toBeTrue();
    expect(entities.some((entityArg) => entityArg.integrationDomain === 'moehlenhoff_alpha2' && entityArg.platform === 'button')).toBeTrue();
    expect(requests.some((requestArg) => requestArg.method === 'GET' && requestArg.url === '/data/static.xml')).toBeTrue();
    expect(requests.some((requestArg) => requestArg.body?.includes('<HEATAREA nr="1"><T_TARGET>21.4</T_TARGET><T_HEAT_DAY>21.4</T_HEAT_DAY></HEATAREA>'))).toBeTrue();
    expect(requests.some((requestArg) => requestArg.body?.includes('<COOLING>1</COOLING>'))).toBeTrue();
    expect(requests.some((requestArg) => requestArg.body?.includes('<DATETIME>2026-01-01T01:02:03</DATETIME>'))).toBeTrue();
    await runtime.destroy();
  } finally {
    await new Promise<void>((resolve, reject) => server.close((errorArg) => errorArg ? reject(errorArg) : resolve()));
  }
});

tap.test('exposes Mohlenhoff Alpha 2 runtime, HA alias, and unsupported control without executor', async () => {
  const integration = new MoehlenhoffAlpha2Integration();
  const alias = new HomeAssistantMoehlenhoffAlpha2Integration();
  expect(alias instanceof MoehlenhoffAlpha2Integration).toBeTrue();
  expect(alias.domain).toEqual("moehlenhoff_alpha2");
  expect(integration.status).toEqual("control-runtime");
  expect(moehlenhoffAlpha2Profile.metadata.configFlow).toEqual(true);
  expect(moehlenhoffAlpha2Profile.metadata.requirements).toEqual([
    "moehlenhoff-alpha2==1.4.0",
  ]);

  const runtime = await integration.setup({ name: "Mohlenhoff Alpha 2 Runtime", rawData }, {});
  const statusResult = await runtime.callService!({ domain: "moehlenhoff_alpha2", service: 'status', target: {} });
  const refresh = await runtime.callService!({ domain: "moehlenhoff_alpha2", service: 'refresh', target: {} });
  const snapshot = statusResult.data as IMoehlenhoffAlpha2Snapshot;

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

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