import { createServer } from 'node:http';
import { expect, tap } from '@git.zone/tstest/tapbundle';
import { HomeAssistantLupusecIntegration, LupusecClient, LupusecConfigFlow, LupusecIntegration, LupusecMapper, createLupusecDiscoveryDescriptor, lupusecProfile, type ILupusecSnapshot, type TLupusecRawData } from '../../ts/integrations/lupusec/index.js';

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

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

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

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

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

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

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

tap.test('reads LUPUSEC XT2 snapshots through the native local HTTP API', async () => {
  const calls: string[] = [];
  const server = createServer((requestArg, responseArg) => {
    const url = new URL(requestArg.url || '/', 'http://127.0.0.1');
    calls.push(`${requestArg.method} ${url.pathname}`);

    if (url.pathname === '/images/model.gif') {
      responseArg.statusCode = 404;
      responseArg.end('not xt1');
      return;
    }

    expect(requestArg.headers.authorization).toEqual(`Basic ${Buffer.from('user:pass').toString('base64')}`);
    responseArg.setHeader('content-type', 'application/json');

    if (url.pathname === '/action/tokenGet') {
      responseArg.end(JSON.stringify({ message: 'token-1' }));
      return;
    }
    expect(requestArg.headers['x-token']).toEqual('token-1');

    if (url.pathname === '/action/panelCondGet') {
      responseArg.end(JSON.stringify({ updates: { mode_a1: '{AREA_MODE_1}', battery: '0' } }));
      return;
    }
    if (url.pathname === '/action/deviceListGet') {
      responseArg.end(JSON.stringify({ senrows: [
        { sid: '5', name: 'Front Door', type: 4, openClose: '1', area: 1 },
        { sid: '9', name: 'Water Sensor', type: 5, cond: '0', area: 1 },
      ] }));
      return;
    }

    responseArg.statusCode = 404;
    responseArg.end(JSON.stringify({ error: 'not found' }));
  });

  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 client = new LupusecClient({ host: '127.0.0.1', port, username: 'user', password: 'pass', timeoutMs: 1000 });
    const snapshot = await client.getSnapshot(true);
    const entities = LupusecMapper.toEntities(snapshot);

    expect(snapshot.online).toBeTrue();
    expect(snapshot.source).toEqual('http');
    expect(snapshot.device.model).toEqual('LUPUSEC XT2');
    expect(entities.find((entityArg) => entityArg.id === 'sensor.lupusec_xt2_alarm_mode')?.state).toEqual('Arm');
    expect(entities.find((entityArg) => entityArg.id === 'binary_sensor.lupusec_xt2_5')?.state).toBeTrue();
    expect(calls.includes('GET /action/tokenGet')).toBeTrue();
    expect(calls.includes('GET /action/deviceListGet')).toBeTrue();
  } finally {
    await new Promise<void>((resolve, reject) => server.close((errorArg) => errorArg ? reject(errorArg) : resolve()));
  }
});

tap.test('exposes Lupus Electronics LUPUSEC runtime, HA alias, and unsupported control without executor', async () => {
  const integration = new LupusecIntegration();
  const alias = new HomeAssistantLupusecIntegration();
  expect(alias instanceof LupusecIntegration).toBeTrue();
  expect(alias.domain).toEqual("lupusec");
  expect(integration.status).toEqual("control-runtime");
  expect(lupusecProfile.metadata.configFlow).toEqual(true);
  expect(lupusecProfile.metadata.requirements).toEqual([
    "lupupy==0.3.2",
  ]);

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

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

  const command = await runtime.callService!({ domain: "lupusec", service: lupusecProfile.controlServices?.[0] || 'turn_on', target: {} });
  expect(command.success).toBeFalse();
  expect(command.error!).toContain('native HTTP support is read-only');
  await runtime.destroy();
});

export default tap.start();
