import { createServer, type IncomingMessage, type ServerResponse } from 'node:http';
import { expect, tap } from '@git.zone/tstest/tapbundle';
import { HomeAssistantOpenevseIntegration, OpenevseClient, OpenevseConfigFlow, OpenevseIntegration, OpenevseMapper, createOpenevseDiscoveryDescriptor, openevseProfile, type IOpenevseSnapshot, type TOpenevseRawData } from '../../ts/integrations/openevse/index.js';

const readBody = async (requestArg: 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');
};

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: TOpenevseRawData = {
  device: {
    id: 'openevse-device-1',
    name: "OpenEVSE Device",
    manufacturer: "OpenEVSE",
    model: "OpenEVSE local integration",
    serialNumber: 'openevse-serial-1',
  },
  entities: [
    { id: 'status', name: 'Status', platform: "number", state: true, attributes: { domain: "openevse" } },
  ],
  online: true,
  updatedAt: '2026-01-01T00:00:00.000Z',
  source: 'manual',
};

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

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

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

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

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

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

tap.test('polls OpenEVSE /status and /config over native HTTP and writes charge_rate', async () => {
  const requests: Array<{ method?: string; path: string; authorization?: string; body?: Record<string, unknown> }> = [];
  const server = createServer((requestArg: IncomingMessage, responseArg: ServerResponse) => {
    void (async () => {
      const url = new URL(requestArg.url || '/', 'http://127.0.0.1');
      let body: Record<string, unknown> | undefined;
      if (requestArg.method === 'POST') {
        body = JSON.parse(await readBody(requestArg)) as Record<string, unknown>;
      }
      requests.push({ method: requestArg.method, path: url.pathname, authorization: requestArg.headers.authorization, body });

      if (url.pathname === '/status') {
        json(responseArg, {
          state: 3,
          elapsed: 120,
          amp: 16,
          voltage: 230,
          pilot: 32,
          power: 3680,
          session_energy: 1234,
          total_energy: 12.5,
          temp: 215,
          srssi: -55,
          gfcicount: 1,
          nogndcount: 2,
          stuckcount: 3,
          uptime: 3600,
          freeram: 42000,
        });
        return;
      }
      if (url.pathname === '/config') {
        json(responseArg, {
          wifi_serial: 'AA:BB:CC:DD:EE:FF',
          hostname: 'OpenEVSE Garage',
          buildenv: 'ESP32',
          version: '4.1.2',
          service: '2',
          min_current_hard: 6,
          max_current_hard: 32,
          max_current_soft: 16,
        });
        return;
      }
      if (url.pathname === '/override' && requestArg.method === 'GET') {
        json(responseArg, { state: 'active', charge_current: 16, max_current: 32 });
        return;
      }
      if (url.pathname === '/override' && requestArg.method === 'POST') {
        json(responseArg, { msg: 'done', config_version: 2 });
        return;
      }

      json(responseArg, { error: 'not_found' }, 404);
    })().catch((errorArg) => {
      responseArg.statusCode = 500;
      responseArg.end(String(errorArg));
    });
  });

  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 OpenevseClient({ url, username: 'user', password: 'pass', timeoutMs: 1000 });
    const snapshot = await client.getSnapshot(true);
    const runtime = await new OpenevseIntegration().setup({ url, username: 'user', password: 'pass', timeoutMs: 1000 }, {});
    const entities = await runtime.entities();
    const chargeRate = entities.find((entityArg) => entityArg.platform === 'number' && entityArg.name === 'Charge Rate')!;
    const command = await runtime.callService!({ domain: 'number', service: 'set_value', target: { entityId: chargeRate.id }, data: { value: 20 } });

    expect(snapshot.online).toBeTrue();
    expect(snapshot.source).toEqual('http');
    expect(snapshot.device.name).toEqual('OpenEVSE Garage');
    expect(snapshot.device.serialNumber).toEqual('AA:BB:CC:DD:EE:FF');
    expect(snapshot.entities.find((entityArg) => entityArg.id === 'status')?.state).toEqual('charging');
    expect(snapshot.entities.find((entityArg) => entityArg.id === 'charging_power')?.state).toEqual(3680);
    expect(chargeRate.state).toEqual(16);
    expect(command.success).toBeTrue();
    expect(requests[0].authorization).toEqual(`Basic ${Buffer.from('user:pass').toString('base64')}`);
    expect(requests.some((requestArg) => requestArg.path === '/status')).toBeTrue();
    expect(requests.some((requestArg) => requestArg.path === '/config')).toBeTrue();
    expect(requests.find((requestArg) => requestArg.method === 'POST' && requestArg.path === '/override')?.body?.charge_current).toEqual(20);
    await runtime.destroy();
  } finally {
    await new Promise<void>((resolve, reject) => server.close((errorArg) => errorArg ? reject(errorArg) : resolve()));
  }
});

tap.test('exposes OpenEVSE runtime, HA alias, and unsupported control without executor', async () => {
  const integration = new OpenevseIntegration();
  const alias = new HomeAssistantOpenevseIntegration();
  expect(alias instanceof OpenevseIntegration).toBeTrue();
  expect(alias.domain).toEqual("openevse");
  expect(integration.status).toEqual("control-runtime");
  expect(openevseProfile.metadata.configFlow).toEqual(true);
  expect(openevseProfile.metadata.requirements).toEqual([
    "python-openevse-http==0.2.5",
  ]);
  expect(openevseProfile.defaultHttpPath).toEqual('/status');

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

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

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