import { createServer, type IncomingMessage, type ServerResponse } from 'node:http';
import { expect, tap } from '@git.zone/tstest/tapbundle';
import { HomeAssistantModernFormsIntegration, ModernFormsClient, ModernFormsConfigFlow, ModernFormsIntegration, ModernFormsMapper, createModernFormsDiscoveryDescriptor, modernFormsProfile, type IModernFormsSnapshot, type TModernFormsRawData } from '../../ts/integrations/modern_forms/index.js';

const json = (responseArg: ServerResponse, valueArg: unknown, statusArg = 200): void => {
  responseArg.statusCode = statusArg;
  responseArg.setHeader('content-type', 'application/json');
  responseArg.end(JSON.stringify(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 rawData: TModernFormsRawData = {
  device: {
    id: 'modern_forms-device-1',
    name: "Modern Forms Device",
    manufacturer: "Modern Forms",
    model: "Modern Forms local integration",
    serialNumber: 'modern_forms-serial-1',
  },
  entities: [
    { id: 'status', name: 'Status', platform: "binary_sensor", state: true, attributes: { domain: "modern_forms" } },
  ],
  online: true,
  updatedAt: '2026-01-01T00:00:00.000Z',
  source: 'manual',
};

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

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

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

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

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

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

tap.test('polls and controls Modern Forms through the documented /mf HTTP API', async () => {
  const requests: Array<{ path: string; body: Record<string, unknown> }> = [];
  const state: Record<string, unknown> = {
    fanOn: true,
    fanSpeed: 3,
    fanDirection: 'forward',
    fanSleepTimer: 0,
    lightOn: false,
    lightBrightness: 25,
    lightSleepTimer: 0,
    awayModeEnabled: false,
    adaptiveLearning: true,
  };
  const info = {
    mac: 'aa:bb:cc:dd:ee:ff',
    deviceName: 'Bedroom Fan',
    fanType: 'Aviator',
    lightType: 'LED',
    firmwareVersion: '1.2.3',
    mainMcuFirmwareVersion: '4.5.6',
  };
  const server = createServer((requestArg: IncomingMessage, responseArg: ServerResponse) => {
    void (async () => {
      const body = JSON.parse(await requestBody(requestArg)) as Record<string, unknown>;
      requests.push({ path: requestArg.url || '/', body });
      if (requestArg.url !== '/mf' || requestArg.method !== 'POST') {
        json(responseArg, { error: 'not_found' }, 404);
        return;
      }
      if (body.queryStaticShadowData) {
        json(responseArg, info);
        return;
      }
      if (body.queryDynamicShadowData && Object.keys(body).length === 1) {
        json(responseArg, state);
        return;
      }
      Object.assign(state, body);
      json(responseArg, state);
    })().catch((errorArg) => json(responseArg, { error: String(errorArg) }, 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 ModernFormsClient({ url, timeoutMs: 1000 });
    const snapshot = await client.getSnapshot(true);
    const lightCommand = await client.execute({ domain: 'light', service: 'turn_on', target: {}, data: { brightness: 128 } });
    const fanCommand = await client.execute({ domain: 'fan', service: 'turn_on', target: {}, data: { percentage: 80, direction: 'reverse' } });
    const switchCommand = await client.execute({ domain: 'switch', service: 'turn_on', target: { entityId: 'switch.bedroom_fan_away_mode' } });
    const runtime = await new ModernFormsIntegration().setup({ url, timeoutMs: 1000 }, {});
    const entities = await runtime.entities();

    expect(snapshot.online).toBeTrue();
    expect(snapshot.source).toEqual('http');
    expect(snapshot.device.serialNumber).toEqual('AABBCCDDEEFF');
    expect(snapshot.entities.some((entityArg) => entityArg.platform === 'fan' && entityArg.state === true)).toBeTrue();
    expect(snapshot.entities.some((entityArg) => entityArg.platform === 'light')).toBeTrue();
    expect(lightCommand.success).toBeTrue();
    expect(fanCommand.success).toBeTrue();
    expect(switchCommand.success).toBeTrue();
    expect(entities.some((entityArg) => entityArg.integrationDomain === 'modern_forms' && entityArg.platform === 'switch')).toBeTrue();
    expect(requests[0]).toEqual({ path: '/mf', body: { queryStaticShadowData: true } });
    expect(requests[1]).toEqual({ path: '/mf', body: { queryDynamicShadowData: true } });
    expect(requests.some((requestArg) => requestArg.body.lightOn === true && requestArg.body.lightBrightness === 50)).toBeTrue();
    expect(requests.some((requestArg) => requestArg.body.fanOn === true && requestArg.body.fanDirection === 'reverse')).toBeTrue();
    expect(requests.some((requestArg) => requestArg.body.awayModeEnabled === true && requestArg.body.queryDynamicShadowData === true)).toBeTrue();
    await runtime.destroy();
  } finally {
    await new Promise<void>((resolve, reject) => server.close((errorArg) => errorArg ? reject(errorArg) : resolve()));
  }
});

tap.test('exposes Modern Forms runtime, HA alias, and unsupported control without executor', async () => {
  const integration = new ModernFormsIntegration();
  const alias = new HomeAssistantModernFormsIntegration();
  expect(alias instanceof ModernFormsIntegration).toBeTrue();
  expect(alias.domain).toEqual("modern_forms");
  expect(integration.status).toEqual("control-runtime");
  expect(modernFormsProfile.metadata.configFlow).toEqual(true);
  expect(modernFormsProfile.metadata.requirements).toEqual([
    "aiomodernforms==0.1.8",
  ]);

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

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

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