import { createServer, type IncomingMessage, type ServerResponse } from 'node:http';
import { expect, tap } from '@git.zone/tstest/tapbundle';
import { HomeAssistantIskraIntegration, IskraClient, IskraConfigFlow, IskraIntegration, IskraMapper, createIskraDiscoveryDescriptor, iskraProfile, type IIskraSnapshot, type TIskraRawData } from '../../ts/integrations/iskra/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: TIskraRawData = {
  device: {
    id: 'iskra-device-1',
    name: "iskra Device",
    manufacturer: "iskra",
    model: "iskra local integration",
    serialNumber: 'iskra-serial-1',
  },
  entities: [
    { id: 'status', name: 'Status', platform: "sensor", state: true, attributes: { domain: "iskra" } },
  ],
  online: true,
  updatedAt: '2026-01-01T00:00:00.000Z',
  source: 'manual',
};

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

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

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

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

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

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

tap.test('reads iskra Smart Gateway snapshots over the local REST API', async () => {
  const requests: Array<{ url?: string; cookie?: string }> = [];
  const server = createServer((requestArg: IncomingMessage, responseArg: ServerResponse) => {
    const url = new URL(requestArg.url || '/', 'http://127.0.0.1');
    requests.push({ url: url.pathname, cookie: requestArg.headers.cookie });

    if (url.pathname === '/api') {
      json(responseArg, { device: { model_type: 'SG', serial_number: 'SG123', description: 'Main Gateway', location: 'Panel', sw_ver: '1.2' } });
      return;
    }
    if (url.pathname === '/api/devices') {
      json(responseArg, { devices: [{ model: 'IE38', serial: 'IE38SER', description: 'Main meter', location: 'Panel', interface: 'RS485' }] });
      return;
    }
    if (url.pathname === '/api/measurement/0') {
      json(responseArg, {
        measurements: {
          Phases: [
            { U: '230 V', I: { value: 5, unit: 'A' }, P: '100 W' },
            { U: '231 V', I: '4 A', P: '110 W' },
            { U: '232 V', I: '3 A', P: '120 W' },
          ],
          Total: { P: '330 W', Q: '12 var', S: '350 VA' },
          Frequency: '50 Hz',
        },
      });
      return;
    }
    if (url.pathname === '/api/counter/0') {
      json(responseArg, { counters: { non_resettable: [{ value: 1234, unit: 'Wh', direction: 'import' }], resettable: [{ value: 56, unit: 'Wh', direction: 'export' }] } });
      return;
    }

    json(responseArg, { error: 'not found' }, 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 config = { url: `http://127.0.0.1:${port}`, protocol: 'rest_api' as const, username: 'admin', password: 'iskra', timeoutMs: 1000 };
    const client = new IskraClient(config);
    const snapshot = await client.getSnapshot(true);
    const runtime = await new IskraIntegration().setup(config, {});
    const entities = await runtime.entities();
    const status = await runtime.callService!({ domain: 'iskra', service: 'status', target: {} });

    expect(snapshot.online).toBeTrue();
    expect(snapshot.source).toEqual('http');
    expect(snapshot.device.serialNumber).toEqual('SG123');
    expect(snapshot.entities.find((entityArg) => entityArg.attributes?.key === 'total_active_power')?.state).toEqual(330);
    expect(snapshot.entities.find((entityArg) => entityArg.attributes?.key === 'phase2_voltage')?.state).toEqual(231);
    expect(snapshot.entities.find((entityArg) => entityArg.attributes?.key === 'non_resettable_counter_1')?.state).toEqual(1234);
    expect(entities.find((entityArg) => entityArg.attributes?.key === 'frequency')?.state).toEqual(50);
    expect(status.success).toBeTrue();
    expect(requests.some((requestArg) => requestArg.url === '/api/measurement/0')).toBeTrue();
    expect(requests.every((requestArg) => requestArg.cookie?.startsWith('Authorization=Basic '))).toBeTrue();
    await runtime.destroy();
  } finally {
    await new Promise<void>((resolve, reject) => server.close((errorArg) => errorArg ? reject(errorArg) : resolve()));
  }
});

tap.test('exposes iskra runtime, HA alias, and unsupported control without executor', async () => {
  const integration = new IskraIntegration();
  const alias = new HomeAssistantIskraIntegration();
  expect(alias instanceof IskraIntegration).toBeTrue();
  expect(alias.domain).toEqual("iskra");
  expect(integration.status).toEqual("read-only-runtime");
  expect(iskraProfile.metadata.configFlow).toEqual(true);
  expect(iskraProfile.metadata.requirements).toEqual([
    "pyiskra==0.1.27",
  ]);
  expect((iskraProfile.metadata.localApi as { implemented: string[] }).implemented.some((entryArg) => entryArg.includes('/api/measurement/{index}'))).toBeTrue();

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

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

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