import { createServer } from 'node:net';
import { expect, tap } from '@git.zone/tstest/tapbundle';
import { HomeAssistantMinecraftServerIntegration, MinecraftServerClient, MinecraftServerConfigFlow, MinecraftServerIntegration, MinecraftServerMapper, createMinecraftServerDiscoveryDescriptor, minecraftServerProfile, type IMinecraftServerSnapshot, type TMinecraftServerRawData } from '../../ts/integrations/minecraft_server/index.js';

const createPacket = (payloadArg: Buffer): Buffer => Buffer.concat([encodeVarInt(payloadArg.length), payloadArg]);

const encodeString = (valueArg: string): Buffer => {
  const value = Buffer.from(valueArg, 'utf8');
  return Buffer.concat([encodeVarInt(value.length), value]);
};

const encodeVarInt = (valueArg: number): Buffer => {
  let value = valueArg >>> 0;
  const bytes: number[] = [];
  while (true) {
    if ((value & ~0x7f) === 0) {
      bytes.push(value);
      break;
    }
    bytes.push((value & 0x7f) | 0x80);
    value >>>= 7;
  }
  return Buffer.from(bytes);
};

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

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

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

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

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

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

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

tap.test('reads Java Edition server-list ping over local TCP', async () => {
  const statusResponse = {
    version: { name: '1.21.8', protocol: 772 },
    players: { max: 20, online: 2, sample: [{ name: 'Alex' }, { name: 'Steve' }] },
    description: { text: 'Hello ', extra: [{ text: 'World' }] },
  };
  const responsePacket = createPacket(Buffer.concat([encodeVarInt(0), encodeString(JSON.stringify(statusResponse))]));
  let requests = 0;
  const server = createServer((socketArg) => {
    socketArg.on('data', () => {
      requests++;
      socketArg.end(responsePacket);
    });
  });

  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 MinecraftServerClient({ address: `127.0.0.1:${port}`, timeoutMs: 1000 });
    const snapshot = await client.getSnapshot(true);
    const runtime = await new MinecraftServerIntegration().setup({ address: `127.0.0.1:${port}`, timeoutMs: 1000 }, {});
    const entities = await runtime.entities();
    const refresh = await runtime.callService!({ domain: 'minecraft_server', service: 'refresh', target: {} });

    expect(snapshot.online).toBeTrue();
    expect(snapshot.source).toEqual('tcp');
    expect(snapshot.entities.find((entityArg) => entityArg.id === 'version')?.state).toEqual('1.21.8');
    expect(snapshot.entities.find((entityArg) => entityArg.id === 'motd')?.state).toEqual('Hello World');
    expect(snapshot.entities.find((entityArg) => entityArg.id === 'players_online')?.attributes?.players_list).toEqual(['Alex', 'Steve']);
    expect(entities.some((entityArg) => entityArg.name === 'Version' && entityArg.state === '1.21.8')).toBeTrue();
    expect(refresh.success).toBeTrue();
    expect(requests > 0).toBeTrue();
    await runtime.destroy();
  } finally {
    await new Promise<void>((resolve, reject) => server.close((errorArg) => errorArg ? reject(errorArg) : resolve()));
  }
});

tap.test('keeps Bedrock Edition explicit because native live polling needs UDP mcstatus behavior', async () => {
  const client = new MinecraftServerClient({ address: '127.0.0.1:19132', serverType: 'Bedrock Edition', timeoutMs: 50 });
  const snapshot = await client.getSnapshot(true);

  expect(snapshot.online).toBeFalse();
  expect(snapshot.error!).toContain('direct Java Edition TCP status only');
  expect((minecraftServerProfile.metadata.localApi as { explicitUnsupported: string[] }).explicitUnsupported.some((valueArg) => valueArg.includes('Bedrock Edition'))).toBeTrue();
});

tap.test('exposes Minecraft Server runtime, HA alias, and unsupported control without executor', async () => {
  const integration = new MinecraftServerIntegration();
  const alias = new HomeAssistantMinecraftServerIntegration();
  expect(alias instanceof MinecraftServerIntegration).toBeTrue();
  expect(alias.domain).toEqual("minecraft_server");
  expect(integration.status).toEqual("read-only-runtime");
  expect(minecraftServerProfile.metadata.configFlow).toEqual(true);
  expect(minecraftServerProfile.metadata.requirements).toEqual([
    "mcstatus==13.1.0",
  ]);

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

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

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