import { createServer, type IncomingMessage, type ServerResponse } from 'node:http';
import { expect, tap } from '@git.zone/tstest/tapbundle';
import { IotawattClient, IotawattConfigFlow, IotawattIntegration, IotawattMapper, createIotawattDiscoveryDescriptor, iotawattProfile, type IIotawattSnapshot, type TIotawattRawData } from '../../ts/integrations/iotawatt/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 rawData: TIotawattRawData = {
  device: {
    id: 'iotawatt-device-1',
    name: "IoTaWatt Device",
    manufacturer: "IoTaWatt",
    model: "IoTaWatt local integration",
    serialNumber: 'iotawatt-serial-1',
  },
  entities: [
    { id: 'status', name: 'Status', platform: "sensor", state: true, attributes: { domain: "iotawatt" } },
  ],
  online: true,
  updatedAt: '2026-01-01T00:00:00.000Z',
  source: 'manual',
};

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

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

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

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

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

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

tap.test('reads IoTaWatt /status and /query over local HTTP', async () => {
  const requests: string[] = [];
  const server = createServer((requestArg: IncomingMessage, responseArg: ServerResponse) => {
    const url = new URL(requestArg.url || '/', 'http://127.0.0.1');
    requests.push(`${url.pathname}?${url.searchParams.toString()}`);
    if (url.pathname === '/status' && url.searchParams.get('wifi') === 'yes') {
      json(responseArg, { wifi: { mac: 'AA:BB:CC:DD:EE:FF' } });
      return;
    }
    if (url.pathname === '/status' && url.searchParams.get('inputs') === 'yes' && url.searchParams.get('outputs') === 'yes') {
      json(responseArg, { inputs: [{ channel: 0 }], outputs: [{ name: 'Solar', units: 'Watts' }] });
      return;
    }
    if (url.pathname === '/query' && url.searchParams.get('show') === 'series') {
      json(responseArg, { series: [{ name: 'Mains', unit: 'Watts' }] });
      return;
    }
    if (url.pathname === '/query' && url.searchParams.get('select') === '[Mains.watts,Solar.watts]') {
      json(responseArg, [[42, -500]]);
      return;
    }
    if (url.pathname === '/query' && url.searchParams.get('select') === '[time.iso,Mains.wh,Solar.wh]') {
      json(responseArg, [['2026-01-01T00:00:00Z', 12345, 6789]]);
      return;
    }
    json(responseArg, { error: 'not_found', select: url.searchParams.get('select') }, 404);
  });

  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 IotawattClient({ url, timeoutMs: 1000, timespanSeconds: 30 });
    const snapshot = await client.getSnapshot(true);
    const runtime = await new IotawattIntegration().setup({ url, timeoutMs: 1000, timespanSeconds: 30 }, {});
    const entities = await runtime.entities();

    expect(snapshot.online).toBeTrue();
    expect(snapshot.source).toEqual('http');
    expect(snapshot.device.serialNumber).toEqual('AABBCCDDEEFF');
    expect(snapshot.entities.find((entityArg) => entityArg.id === 'input_0')?.state).toEqual(42);
    expect(snapshot.entities.find((entityArg) => entityArg.id === 'input_0_total_energy')?.state).toEqual(12345);
    expect(entities.some((entityArg) => entityArg.state === -500 && entityArg.name === 'Solar')).toBeTrue();
    expect(requests.some((requestArg) => requestArg.includes('show=series'))).toBeTrue();
    await runtime.destroy();
  } finally {
    await new Promise<void>((resolve, reject) => server.close((errorArg) => errorArg ? reject(errorArg) : resolve()));
  }
});

tap.test('exposes IoTaWatt runtime and unsupported control without executor', async () => {
  const integration = new IotawattIntegration();
  expect(integration.status).toEqual("read-only-runtime");
  expect(iotawattProfile.metadata.configFlow).toEqual(true);
  expect(iotawattProfile.metadata.requirements).toEqual([
    "ha-iotawattpy==0.1.2",
  ]);

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

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

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