import { createServer, type IncomingMessage, type ServerResponse } from 'node:http';
import { expect, tap } from '@git.zone/tstest/tapbundle';
import { HomeAssistantPanasonicVieraIntegration, PanasonicVieraClient, PanasonicVieraConfigFlow, PanasonicVieraIntegration, PanasonicVieraMapper, createPanasonicVieraDiscoveryDescriptor, panasonicVieraProfile, type IPanasonicVieraSnapshot, type TPanasonicVieraRawData } from '../../ts/integrations/panasonic_viera/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 xml = (responseArg: ServerResponse, valueArg: string, statusArg = 200): void => {
  responseArg.statusCode = statusArg;
  responseArg.setHeader('content-type', 'text/xml');
  responseArg.end(valueArg);
};

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

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

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

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

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

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

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

tap.test('reads and controls Panasonic Viera through SOAP over local HTTP', async () => {
  const requests: Array<{ method?: string; url?: string; body?: string; soapAction?: string }> = [];
  const server = createServer((requestArg: IncomingMessage, responseArg: ServerResponse) => {
    void (async () => {
      const body = requestArg.method === 'POST' ? await readBody(requestArg) : undefined;
      requests.push({ method: requestArg.method, url: requestArg.url, body, soapAction: requestArg.headers.soapaction as string | undefined });
      const url = new URL(requestArg.url || '/', 'http://127.0.0.1');

      if (requestArg.method === 'GET' && url.pathname === '/nrc/ddd.xml') {
        xml(responseArg, '<root><device><friendlyName>Living Room TV</friendlyName><manufacturer>Panasonic</manufacturer><modelName>Viera ST</modelName><modelNumber>TX-55</modelNumber><UDN>uuid:tv-1</UDN></device></root>');
        return;
      }
      if (requestArg.method === 'POST' && url.pathname === '/dmr/control_0' && body?.includes('GetVolume')) {
        xml(responseArg, '<s:Envelope><s:Body><u:GetVolumeResponse><CurrentVolume>37</CurrentVolume></u:GetVolumeResponse></s:Body></s:Envelope>');
        return;
      }
      if (requestArg.method === 'POST' && url.pathname === '/dmr/control_0' && body?.includes('GetMute')) {
        xml(responseArg, '<s:Envelope><s:Body><u:GetMuteResponse><CurrentMute>0</CurrentMute></u:GetMuteResponse></s:Body></s:Envelope>');
        return;
      }
      if (requestArg.method === 'POST' && url.pathname === '/nrc/control_0' && body?.includes('X_SendKey')) {
        xml(responseArg, '<s:Envelope><s:Body><u:X_SendKeyResponse /></s:Body></s:Envelope>');
        return;
      }
      xml(responseArg, '<error>not found</error>', 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 PanasonicVieraClient({ url, timeoutMs: 1000 });
    const snapshot = await client.getSnapshot(true);
    const command = await client.execute({ domain: 'panasonic_viera', service: 'volume_up', target: {} });
    const runtime = await new PanasonicVieraIntegration().setup({ url, timeoutMs: 1000 }, {});
    const status = await runtime.callService!({ domain: 'panasonic_viera', service: 'status', target: {} });

    expect(snapshot.online).toBeTrue();
    expect(snapshot.source).toEqual('http');
    expect(snapshot.device.name).toEqual('Living Room TV');
    expect(snapshot.device.serialNumber).toEqual('uuid:tv-1');
    expect(snapshot.entities.find((entityArg) => entityArg.id === 'volume')?.state).toEqual(37);
    expect(command.success).toBeTrue();
    expect(status.success).toBeTrue();
    expect(requests.some((requestArg) => requestArg.body?.includes('NRC_VOLUP-ONOFF'))).toBeTrue();
    await runtime.destroy();
  } finally {
    await new Promise<void>((resolve, reject) => server.close((errorArg) => errorArg ? reject(errorArg) : resolve()));
  }
});

tap.test('exposes Panasonic Viera runtime, HA alias, and unsupported control without executor', async () => {
  const integration = new PanasonicVieraIntegration();
  const alias = new HomeAssistantPanasonicVieraIntegration();
  expect(alias instanceof PanasonicVieraIntegration).toBeTrue();
  expect(alias.domain).toEqual("panasonic_viera");
  expect(integration.status).toEqual("control-runtime");
  expect(panasonicVieraProfile.metadata.configFlow).toEqual(true);
  expect(panasonicVieraProfile.metadata.requirements).toEqual([
    "panasonic-viera==0.4.4",
  ]);

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

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

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