import { createServer, type IncomingMessage, type ServerResponse } from 'node:http';
import { expect, tap } from '@git.zone/tstest/tapbundle';
import { HomeAssistantPhilipsJsIntegration, PhilipsJsClient, PhilipsJsConfigFlow, PhilipsJsIntegration, PhilipsJsMapper, createPhilipsJsDiscoveryDescriptor, philipsJsProfile, type IPhilipsJsSnapshot, type TPhilipsJsRawData } from '../../ts/integrations/philips_js/index.js';

const json = (responseArg: ServerResponse, valueArg: unknown, statusArg = 200, headersArg: Record<string, string> = {}): void => {
  responseArg.statusCode = statusArg;
  responseArg.setHeader('content-type', 'application/json');
  for (const [key, value] of Object.entries(headersArg)) {
    responseArg.setHeader(key, value);
  }
  responseArg.end(JSON.stringify(valueArg));
};

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

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

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

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

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

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

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

tap.test('reads and controls Philips TV through native JointSpace HTTP with digest retry', async () => {
  const requests: Array<{ method?: string; url?: string; authorization?: string; body?: string }> = [];
  const server = createServer((requestArg: IncomingMessage, responseArg: ServerResponse) => {
    const chunks: Buffer[] = [];
    requestArg.on('data', (chunkArg) => chunks.push(Buffer.isBuffer(chunkArg) ? chunkArg : Buffer.from(chunkArg)));
    requestArg.on('end', () => {
      const body = Buffer.concat(chunks).toString('utf8');
      requests.push({ method: requestArg.method, url: requestArg.url, authorization: requestArg.headers.authorization, body });
      const url = new URL(requestArg.url || '/', 'http://127.0.0.1');
      if (requestArg.method === 'GET' && url.pathname === '/1/system') {
        json(responseArg, {
          name: 'Living Philips',
          serialnumber: 'TVSERIAL123',
          softwareversion: 'TPM1',
          model: '55PFL6007T/12',
          api_version: { Major: 1, Minor: 0, Patch: 0 },
          featuring: { jsonfeatures: { ambilight: ['LoungeLight'], inputkey: ['key'] }, systemfeatures: { secured_transport: false } },
        });
        return;
      }
      if (requestArg.method === 'GET' && url.pathname === '/1/powerstate') {
        json(responseArg, { powerstate: 'On' });
        return;
      }
      if (requestArg.method === 'GET' && url.pathname === '/1/audio/volume') {
        json(responseArg, { muted: false, current: 12, min: 0, max: 60 });
        return;
      }
      if (requestArg.method === 'GET' && url.pathname === '/1/sources') {
        json(responseArg, { hdmi1: { name: 'HDMI 1' }, tv: { name: 'Watch TV' } });
        return;
      }
      if (requestArg.method === 'GET' && url.pathname === '/1/sources/current') {
        json(responseArg, { id: 'hdmi1' });
        return;
      }
      if (requestArg.method === 'GET' && url.pathname === '/1/channels/current') {
        json(responseArg, { id: 'channel-1' });
        return;
      }
      if (requestArg.method === 'GET' && url.pathname === '/1/ambilight/mode') {
        json(responseArg, { current: 'internal' });
        return;
      }
      if (requestArg.method === 'POST' && url.pathname === '/1/input/key') {
        if (!requestArg.headers.authorization) {
          json(responseArg, { error: 'auth' }, 401, { 'www-authenticate': 'Digest realm="philips", nonce="abcdef", qop="auth", algorithm=MD5' });
          return;
        }
        json(responseArg, {});
        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 config = { host: '127.0.0.1', port, apiVersion: 1, timeoutMs: 1000, username: 'user', password: 'pass' };
    const client = new PhilipsJsClient(config);
    const snapshot = await client.getSnapshot(true);
    const runtime = await new PhilipsJsIntegration().setup(config, {});
    const entities = await runtime.entities();
    const command = await runtime.callService!({ domain: 'remote', service: 'send_command', target: {}, data: { command: 'Standby' } });

    expect(snapshot.online).toBeTrue();
    expect(snapshot.source).toEqual('http');
    expect(snapshot.device.serialNumber).toEqual('TVSERIAL123');
    expect(snapshot.entities.find((entityArg) => entityArg.id === 'media_player')?.attributes?.volumeLevel).toEqual(0.2);
    expect(snapshot.entities.find((entityArg) => entityArg.id === 'media_player')?.attributes?.source).toEqual('HDMI 1');
    expect(entities.some((entityArg) => entityArg.platform === 'media_player' && entityArg.state === 'on')).toBeTrue();
    expect(command.success).toBeTrue();
    expect(requests.some((requestArg) => requestArg.url === '/1/input/key' && !requestArg.authorization)).toBeTrue();
    expect(requests.some((requestArg) => requestArg.url === '/1/input/key' && requestArg.authorization?.startsWith('Digest ') && requestArg.body === '{"key":"Standby"}')).toBeTrue();
    await runtime.destroy();
  } finally {
    await new Promise<void>((resolve, reject) => server.close((errorArg) => errorArg ? reject(errorArg) : resolve()));
  }
});

tap.test('exposes Philips TV runtime, HA alias, and unsupported control without executor', async () => {
  const integration = new PhilipsJsIntegration();
  const alias = new HomeAssistantPhilipsJsIntegration();
  expect(alias instanceof PhilipsJsIntegration).toBeTrue();
  expect(alias.domain).toEqual("philips_js");
  expect(integration.status).toEqual("control-runtime");
  expect(philipsJsProfile.metadata.configFlow).toEqual(true);
  expect(philipsJsProfile.metadata.requirements).toEqual([
    "ha-philipsjs==3.2.4",
  ]);
  expect(JSON.stringify(philipsJsProfile.metadata.localApi)).toContain('/<api>/system');
  expect(JSON.stringify(philipsJsProfile.metadata.localApi)).toContain('digest_auth_pairing');

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

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

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