import { expect, tap } from '@git.zone/tstest/tapbundle';
import * as http from 'node:http';
import type { AddressInfo } from 'node:net';
import { HomeAssistantIzoneIntegration, IzoneClient, IzoneConfigFlow, IzoneIntegration, IzoneMapper, createIzoneDiscoveryDescriptor, izoneProfile, type IIzoneSnapshot, type TIzoneRawData } from '../../ts/integrations/izone/index.js';

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

const listen = async (serverArg: http.Server): Promise<number> => await new Promise((resolveArg) => {
  serverArg.listen(0, '127.0.0.1', () => resolveArg((serverArg.address() as AddressInfo).port));
});

const close = async (serverArg: http.Server): Promise<void> => await new Promise((resolveArg, rejectArg) => {
  serverArg.close((errorArg) => errorArg ? rejectArg(errorArg) : resolveArg());
});

const readBody = async (requestArg: http.IncomingMessage): Promise<string> => {
  const chunks: Buffer[] = [];
  for await (const chunk of requestArg) {
    chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
  }
  return Buffer.concat(chunks).toString('utf8');
};

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

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

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

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

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

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

tap.test('polls iZone HTTP resources and sends native raw TCP HTTP command', async () => {
  const requests: Array<{ method?: string; url?: string; body?: unknown }> = [];
  const server = http.createServer(async (requestArg, responseArg) => {
    responseArg.setHeader('content-type', 'application/json');
    if (requestArg.method === 'GET' && requestArg.url === '/SystemSettings') {
      requests.push({ method: requestArg.method, url: requestArg.url });
      responseArg.end(JSON.stringify({ AirStreamDeviceUId: '000013170', SysOn: 'on', SysMode: 'cool', SysFan: 'medium', FanAuto: '3-speed', NoOfZones: 2, Supply: 12.3, Setpoint: 22, Temp: 23.5, EcoLock: 'false', EcoMin: 15, EcoMax: 30, RAS: 'master', CtrlZone: 1, NoOfConst: 0, SysType: '310', FreeAir: 'off' }));
      return;
    }
    if (requestArg.method === 'GET' && requestArg.url === '/Zones1_4') {
      requests.push({ method: requestArg.method, url: requestArg.url });
      responseArg.end(JSON.stringify([
        { Index: 0, Name: 'Living', Type: 'auto', Mode: 'auto', SetPoint: 22, Temp: 23, MaxAir: 80, MinAir: 20 },
        { Index: 1, Name: 'Bed', Type: 'opcl', Mode: 'open', SetPoint: 0, Temp: 0, MaxAir: 100, MinAir: 10 },
      ]));
      return;
    }
    if (requestArg.method === 'POST' && requestArg.url === '/AirMinCommand') {
      const body = JSON.parse(await readBody(requestArg)) as unknown;
      requests.push({ method: requestArg.method, url: requestArg.url, body });
      responseArg.end('{"ok":true}{OK}');
      return;
    }
    requests.push({ method: requestArg.method, url: requestArg.url });
    responseArg.statusCode = 404;
    responseArg.end(JSON.stringify({ error: 'not found' }));
  });
  const port = await listen(server);
  try {
    const client = new IzoneClient({ host: '127.0.0.1', port });
    const snapshot = await client.getSnapshot(true);
    const command = await client.execute({ domain: 'izone', service: 'airflow_min', target: {}, data: { zoneNo: 1, airflow: 25 } });

    expect(snapshot.source).toEqual('http');
    expect(snapshot.device.id).toEqual('000013170');
    expect(snapshot.entities.some((entityArg) => entityArg.id === 'controller' && entityArg.state === 'cool')).toBeTrue();
    expect(snapshot.entities.some((entityArg) => entityArg.id === 'zone_1' && entityArg.state === 'heat_cool')).toBeTrue();
    expect(command.success).toBeTrue();
    expect(requests.some((requestArg) => requestArg.method === 'GET' && requestArg.url === '/SystemSettings')).toBeTrue();
    expect(requests.some((requestArg) => requestArg.method === 'GET' && requestArg.url === '/Zones1_4')).toBeTrue();
    expect(requests.some((requestArg) => requestArg.method === 'POST' && requestArg.url === '/AirMinCommand' && JSON.stringify(requestArg.body) === JSON.stringify({ AirMinCommand: { ZoneNo: '1', Command: '25' } }))).toBeTrue();
  } finally {
    await close(server);
  }
});

tap.test('exposes iZone runtime, HA alias, and unsupported control without executor', async () => {
  const integration = new IzoneIntegration();
  const alias = new HomeAssistantIzoneIntegration();
  expect(alias instanceof IzoneIntegration).toBeTrue();
  expect(alias.domain).toEqual("izone");
  expect(integration.status).toEqual("control-runtime");
  expect(izoneProfile.metadata.configFlow).toEqual(true);
  expect(izoneProfile.metadata.requirements).toEqual([
    "python-izone==1.2.9",
  ]);

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

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

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