import { createServer as createHttpServer } from 'node:http';
import { createServer as createNetServer } from 'node:net';
import { expect, tap } from '@git.zone/tstest/tapbundle';
import { HomeAssistantLutronIntegration, LutronClient, LutronConfigFlow, LutronIntegration, LutronMapper, createLutronDiscoveryDescriptor, lutronProfile, type ILutronSnapshot, type TLutronRawData } from '../../ts/integrations/lutron/index.js';

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

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

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

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

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

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

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

tap.test('reads RadioRA 2 XML over HTTP, queries Telnet levels, and writes Telnet commands', async () => {
  const httpCalls: string[] = [];
  const telnetCommands: string[] = [];
  const xml = `<?xml version="1.0"?>
<Project>
  <GUID>0123456789abcdef</GUID>
  <OccupancyGroups><OccupancyGroup OccupancyGroupNumber="1" UUID="occ-1" /></OccupancyGroups>
  <Areas>
    <Area Name="Demo Project">
      <Areas>
        <Area Name="Living" IntegrationID="2" OccupancyGroupAssignedToID="1">
          <Outputs>
            <Output Name="Pendant" OutputType="INC" IntegrationID="5" Wattage="100" UUID="out-5" />
            <Output Name="Shade" OutputType="SYSTEM_SHADE" IntegrationID="6" UUID="out-6" />
          </Outputs>
          <DeviceGroups>
            <DeviceGroup Name="Wall">
              <Devices>
                <Device Name="Keypad" DeviceType="SEETOUCH_KEYPAD" IntegrationID="10" UUID="keypad-10">
                  <Components>
                    <Component ComponentType="BUTTON" ComponentNumber="1"><Button Engraving="Relax" ButtonType="SingleAction" UUID="button-1" /></Component>
                  </Components>
                </Device>
              </Devices>
            </DeviceGroup>
          </DeviceGroups>
        </Area>
      </Areas>
    </Area>
  </Areas>
</Project>`;

  const httpServer = createHttpServer((requestArg, responseArg) => {
    httpCalls.push(requestArg.url || '');
    if (requestArg.url === '/DbXmlInfo.xml') {
      responseArg.setHeader('content-type', 'application/xml');
      responseArg.end(xml);
      return;
    }
    responseArg.statusCode = 404;
    responseArg.end('not found');
  });

  const telnetServer = createNetServer((socketArg) => {
    socketArg.setEncoding('utf8');
    let stage: 'username' | 'password' | 'commands' = 'username';
    socketArg.write('login: ');
    socketArg.on('data', (chunkArg) => {
      const text = String(chunkArg);
      if (stage === 'username') {
        expect(text.trim()).toEqual('lutron');
        stage = 'password';
        socketArg.write('password: ');
        return;
      }
      if (stage === 'password') {
        expect(text.trim()).toEqual('integration');
        stage = 'commands';
        socketArg.write('GNET>');
        return;
      }
      for (const command of text.split(/\r?\n/).map((lineArg) => lineArg.trim()).filter(Boolean)) {
        telnetCommands.push(command);
        if (command === '?OUTPUT,5,1') {
          socketArg.write('~OUTPUT,5,1,75\r\nGNET>');
        } else if (command === '?OUTPUT,6,1') {
          socketArg.write('~OUTPUT,6,1,20\r\nGNET>');
        } else {
          socketArg.write('GNET>');
        }
      }
    });
  });

  await new Promise<void>((resolve) => httpServer.listen(0, '127.0.0.1', resolve));
  await new Promise<void>((resolve) => telnetServer.listen(0, '127.0.0.1', resolve));
  try {
    const httpAddress = httpServer.address();
    const telnetAddress = telnetServer.address();
    const httpPort = typeof httpAddress === 'object' && httpAddress ? httpAddress.port : 0;
    const telnetPort = typeof telnetAddress === 'object' && telnetAddress ? telnetAddress.port : 0;
    const config = { host: '127.0.0.1', httpPort, telnetPort, username: 'lutron', password: 'integration', timeoutMs: 1000 };
    const client = new LutronClient(config);
    const snapshot = await client.getSnapshot(true);
    const runtime = await new LutronIntegration().setup(config, {});
    const entities = await runtime.entities();
    const command = await runtime.callService!({ domain: 'light', service: 'turn_off', target: {}, data: { integrationId: 5 } });

    expect(snapshot.online).toBeTrue();
    expect(snapshot.source).toEqual('http');
    expect(snapshot.device.serialNumber).toEqual('0123456789abcdef');
    expect(snapshot.entities.find((entityArg) => entityArg.id === 'output_5')?.state).toBeTrue();
    expect(snapshot.entities.find((entityArg) => entityArg.id === 'output_6')?.state).toEqual(20);
    expect(entities.some((entityArg) => entityArg.platform === 'button' && entityArg.name.includes('Relax'))).toBeTrue();
    expect(command.success).toBeTrue();
    expect(httpCalls.includes('/DbXmlInfo.xml')).toBeTrue();
    expect(telnetCommands.includes('?OUTPUT,5,1')).toBeTrue();
    expect(telnetCommands.includes('#OUTPUT,5,1,0')).toBeTrue();
    await runtime.destroy();
  } finally {
    await new Promise<void>((resolve, reject) => httpServer.close((errorArg) => errorArg ? reject(errorArg) : resolve()));
    await new Promise<void>((resolve, reject) => telnetServer.close((errorArg) => errorArg ? reject(errorArg) : resolve()));
  }
});

tap.test('exposes Lutron runtime, HA alias, and unsupported control without executor', async () => {
  const integration = new LutronIntegration();
  const alias = new HomeAssistantLutronIntegration();
  expect(alias instanceof LutronIntegration).toBeTrue();
  expect(alias.domain).toEqual("lutron");
  expect(integration.status).toEqual("control-runtime");
  expect(lutronProfile.metadata.configFlow).toEqual(true);
  expect(lutronProfile.metadata.requirements).toEqual([
    "pylutron==0.4.1",
  ]);

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

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

  const command = await runtime.callService!({ domain: "lutron", service: lutronProfile.controlServices?.[0] || 'turn_on', target: {} });
  expect(command.success).toBeFalse();
  expect(command.error!).toContain('live writes require host, username, password');
  await runtime.destroy();
});

export default tap.start();
