import { createServer } from 'node:http';
import { expect, tap } from '@git.zone/tstest/tapbundle';
import { HomeAssistantPanasonicBlurayIntegration, PanasonicBlurayClient, PanasonicBlurayConfigFlow, PanasonicBlurayIntegration, PanasonicBlurayMapper, createPanasonicBlurayDiscoveryDescriptor, panasonicBlurayProfile, type IPanasonicBluraySnapshot, type TPanasonicBlurayRawData } from '../../ts/integrations/panasonic_bluray/index.js';

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

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

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

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

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

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

  expect(snapshot.online).toBeTrue();
  expect(mappedSnapshot.source).toEqual('manual');
  expect(devices[0].integrationDomain).toEqual("panasonic_bluray");
  expect(devices[0].manufacturer).toEqual("Panasonic Blu-Ray Player");
  expect(entities.some((entityArg) => entityArg.integrationDomain === "panasonic_bluray" && entityArg.platform === "media_player")).toBeTrue();
});

tap.test('polls and controls Panasonic Blu-Ray over the local panacotta HTTP API', async () => {
  const bodies: string[] = [];
  const server = createServer((requestArg, responseArg) => {
    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');
      bodies.push(body);
      responseArg.setHeader('content-type', 'text/plain');
      if (requestArg.url !== '/WAN/dvdr/dvdr_ctrl.cgi') {
        responseArg.statusCode = 404;
        responseArg.end('not found');
        return;
      }
      if (body.includes('cCMD_PST.x=100')) {
        responseArg.end('00, "", 1\r\n1,120,0,0');
        return;
      }
      if (body.includes('cCMD_GET_STATUS.x=100')) {
        responseArg.end('00, "", 1\r\n0,0,0,248,3600,1,8,2,0,00000000');
        return;
      }
      if (body.includes('cCMD_RC_PAUSE.x=100')) {
        responseArg.end('00, "", 1\r\n');
        return;
      }
      responseArg.end('FE, "", 1\r\n');
    });
  });

  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 PanasonicBlurayClient({ host: '127.0.0.1', port, timeoutMs: 1000 });
    const snapshot = await client.getSnapshot();

    expect(snapshot.online).toBeTrue();
    expect(snapshot.source).toEqual('http');
    expect(snapshot.entities[0].state).toEqual('playing');
    expect(snapshot.entities[0].attributes?.mediaPosition).toEqual(120);
    expect(snapshot.entities[0].attributes?.mediaDuration).toEqual(3600);

    const pause = await client.execute({ domain: 'media_player', service: 'media_pause', target: {} });
    expect(pause.success).toBeTrue();
    expect(bodies.some((bodyArg) => bodyArg.includes('cCMD_RC_PAUSE.x=100'))).toBeTrue();
  } finally {
    await new Promise<void>((resolve, reject) => server.close((errorArg) => errorArg ? reject(errorArg) : resolve()));
  }
});

tap.test('exposes Panasonic Blu-Ray Player runtime, HA alias, and unsupported control without executor', async () => {
  const integration = new PanasonicBlurayIntegration();
  const alias = new HomeAssistantPanasonicBlurayIntegration();
  expect(alias instanceof PanasonicBlurayIntegration).toBeTrue();
  expect(alias.domain).toEqual("panasonic_bluray");
  expect(integration.status).toEqual("control-runtime");
  expect(panasonicBlurayProfile.metadata.configFlow).toEqual(false);
  expect(panasonicBlurayProfile.metadata.requirements).toEqual([
    "panacotta==0.2",
  ]);

  const runtime = await integration.setup({ name: "Panasonic Blu-Ray Player Runtime", rawData }, {});
  const statusResult = await runtime.callService!({ domain: "panasonic_bluray", service: 'status', target: {} });
  const refresh = await runtime.callService!({ domain: "panasonic_bluray", service: 'refresh', target: {} });
  const snapshot = statusResult.data as IPanasonicBluraySnapshot;

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

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