import * as http from 'node:http';
import { expect, tap } from '@git.zone/tstest/tapbundle';
import { HomeAssistantMystromIntegration, MystromClient, MystromConfigFlow, MystromIntegration, MystromMapper, createMystromDiscoveryDescriptor, mystromProfile, type IMystromSnapshot, type TMystromRawData } from '../../ts/integrations/mystrom/index.js';

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

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

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

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

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

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

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

tap.test('exposes myStrom runtime, HA alias, and unsupported control without executor', async () => {
  const integration = new MystromIntegration();
  const alias = new HomeAssistantMystromIntegration();
  expect(alias instanceof MystromIntegration).toBeTrue();
  expect(alias.domain).toEqual("mystrom");
  expect(integration.status).toEqual("control-runtime");
  expect(mystromProfile.metadata.configFlow).toEqual(true);
  expect(mystromProfile.metadata.requirements).toEqual([
    "python-mystrom==2.5.0",
  ]);

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

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

  const command = await runtime.callService!({ domain: "mystrom", service: mystromProfile.controlServices?.[0] || 'turn_on', target: {} });
  expect(command.success).toBeFalse();
  expect(command.error!).toContain('requires config.host/config.url');
  await runtime.destroy();
});

tap.test('polls and controls myStrom switches through local HTTP endpoints', async () => {
  const requests: string[] = [];
  const server = http.createServer((request, response) => {
    requests.push(request.url || '');
    response.setHeader('content-type', 'application/json');
    if (request.url === '/api/v1/info') {
      response.end(JSON.stringify({ ip: '127.0.0.1', mac: 'AABBCCDDEEFF', type: 101, version: '2.99' }));
      return;
    }
    if (request.url === '/report') {
      response.end(JSON.stringify({ relay: true, power: 12.3, Ws: 2.1, energy_since_boot: 456, temperature: 22.4 }));
      return;
    }
    if (request.url === '/relay?state=0') {
      response.end(JSON.stringify({ ok: true }));
      return;
    }
    response.statusCode = 404;
    response.end(JSON.stringify({ error: 'not found' }));
  });

  await listen(server);
  try {
    const address = server.address();
    const port = typeof address === 'object' && address ? address.port : 0;
    const client = new MystromClient({ host: '127.0.0.1', port, timeoutMs: 1000 });
    const snapshot = await client.getSnapshot(true);
    const command = await client.execute({ domain: 'switch', service: 'turn_off', target: {}, data: {} });

    expect(snapshot.online).toBeTrue();
    expect(snapshot.source).toEqual('http');
    expect(snapshot.entities.some((entityArg) => entityArg.platform === 'switch' && entityArg.state === true)).toBeTrue();
    expect(snapshot.entities.some((entityArg) => entityArg.id === 'consumption' && entityArg.state === 12.3)).toBeTrue();
    expect(command.success).toBeTrue();
    expect(requests).toContain('/relay?state=0');
  } finally {
    await close(server);
  }
});

const listen = (serverArg: http.Server): Promise<void> => new Promise((resolve) => serverArg.listen(0, '127.0.0.1', () => resolve()));
const close = (serverArg: http.Server): Promise<void> => new Promise((resolve, reject) => serverArg.close((errorArg) => errorArg ? reject(errorArg) : resolve()));

export default tap.start();
