import { createServer, type IncomingMessage, type ServerResponse } from 'node:http';
import { expect, tap } from '@git.zone/tstest/tapbundle';
import { HomeAssistantOtbrIntegration, OtbrClient, OtbrConfigFlow, OtbrIntegration, OtbrMapper, createOtbrDiscoveryDescriptor, otbrProfile, type IOtbrSnapshot, type TOtbrRawData } from '../../ts/integrations/otbr/index.js';

const rawData: TOtbrRawData = {
  device: {
    id: 'otbr-device-1',
    name: "Open Thread Border Router Device",
    manufacturer: "Open Thread Border Router",
    model: "Open Thread Border Router local integration",
    serialNumber: 'otbr-serial-1',
  },
  entities: [
    { id: 'status', name: 'Status', platform: "sensor", state: true, attributes: { domain: "otbr" } },
  ],
  online: true,
  updatedAt: '2026-01-01T00:00:00.000Z',
  source: 'manual',
};

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

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

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

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

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

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

tap.test('reads Open Thread Border Router local REST API snapshots', async () => {
  const requests: string[] = [];
  const server = createServer((requestArg: IncomingMessage, responseArg: ServerResponse) => {
    const url = new URL(requestArg.url || '/', 'http://127.0.0.1');
    requests.push(`${requestArg.method} ${url.pathname} ${requestArg.headers.accept || ''}`);
    if (url.pathname === '/api/actions') {
      json(responseArg, {});
      return;
    }
    if (url.pathname === '/node/ba-id') {
      json(responseArg, '00112233445566778899aabbccddeeff');
      return;
    }
    if (url.pathname === '/node/ext-address') {
      json(responseArg, '0102030405060708');
      return;
    }
    if (url.pathname === '/node/coprocessor/version') {
      json(responseArg, 'OTBR-test');
      return;
    }
    if (url.pathname === '/node/dataset/active' && requestArg.headers.accept === 'text/plain') {
      responseArg.setHeader('content-type', 'text/plain');
      responseArg.end('000300000f0307546573744e6574');
      return;
    }
    if (url.pathname === '/node/dataset/active') {
      json(responseArg, { channel: 15, networkName: 'TestNet', panId: '1234' });
      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 url = `http://127.0.0.1:${port}`;
    const client = new OtbrClient({ url, timeoutMs: 1000 });
    const snapshot = await client.getSnapshot(true);
    const runtime = await new OtbrIntegration().setup({ url, timeoutMs: 1000 }, {});
    const status = await runtime.callService!({ domain: 'otbr', service: 'status', target: {} });

    expect(snapshot.online).toBeTrue();
    expect(snapshot.source).toEqual('http');
    expect(snapshot.entities.find((entityArg) => entityArg.id === 'border_agent_id')?.state).toEqual('00112233445566778899aabbccddeeff');
    expect(snapshot.entities.find((entityArg) => entityArg.id === 'channel')?.state).toEqual(15);
    expect(snapshot.entities.find((entityArg) => entityArg.id === 'network_name')?.state).toEqual('TestNet');
    expect(status.success).toBeTrue();
    expect(requests.some((requestArg) => requestArg.includes('/api/actions'))).toBeTrue();
    expect(requests.some((requestArg) => requestArg.includes('/node/dataset/active text/plain'))).toBeTrue();
    await runtime.destroy();
  } finally {
    await new Promise<void>((resolve, reject) => server.close((errorArg) => errorArg ? reject(errorArg) : resolve()));
  }
});

tap.test('exposes Open Thread Border Router runtime, HA alias, and unsupported control without executor', async () => {
  const integration = new OtbrIntegration();
  const alias = new HomeAssistantOtbrIntegration();
  expect(alias instanceof OtbrIntegration).toBeTrue();
  expect(alias.domain).toEqual("otbr");
  expect(integration.status).toEqual("read-only-runtime");
  expect(otbrProfile.metadata.configFlow).toEqual(true);
  expect(otbrProfile.metadata.requirements).toEqual([
    "python-otbr-api==2.10.0",
  ]);

  const runtime = await integration.setup({ name: "Open Thread Border Router Runtime", rawData }, {});
  const statusResult = await runtime.callService!({ domain: "otbr", service: 'status', target: {} });
  const refresh = await runtime.callService!({ domain: "otbr", service: 'refresh', target: {} });
  const snapshot = statusResult.data as IOtbrSnapshot;

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

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

const json = (responseArg: ServerResponse, valueArg: unknown, statusArg = 200): void => {
  responseArg.statusCode = statusArg;
  responseArg.setHeader('content-type', 'application/json');
  responseArg.end(JSON.stringify(valueArg));
};

export default tap.start();
