import { expect, test } from 'bun:test';
import CS from '../../capstone';

test('CS.ARCH_M68K', () => {
  const buffer = new Uint8Array([
    0x48, 0x32, 0x12, 0x34, 0x56, 0x78, 0xd2, 0x2a, 0xab, 0xcd, 0x54, 0x03,
    0x00, 0x00, 0x4c, 0x38, 0x00, 0x01, 0x4c, 0x0a, 0x00, 0x02, 0xd0, 0x2c,
    0x4c, 0x0c, 0x00, 0x04, 0xd0, 0x2c, 0x4c, 0xfe, 0x00, 0x00, 0x00, 0x00,
    0x12, 0x34, 0x56, 0x78, 0x32, 0x60, 0x4e, 0x00, 0x00, 0x11, 0x32, 0x61,
    0x4e, 0x00, 0x00, 0x11, 0x32, 0x62, 0x4e, 0x00, 0x00, 0x11, 0xd3, 0xc0,
    0x4c, 0x07, 0x00, 0x11, 0xd4, 0xc0, 0x4c, 0x06, 0x00, 0x11, 0xd5, 0xc0,
    0x4c, 0x05, 0x00, 0x11, 0xd6, 0xc0, 0x4c, 0x04, 0x00, 0x11, 0xd7, 0xc0,
    0x4c, 0x03, 0x00, 0x11, 0x42, 0x00, 0x4e, 0x71, 0x42, 0x41, 0x4e, 0x71,
    0x42, 0x42, 0x4e, 0x71, 0x46, 0x00, 0x4e, 0x71, 0x46, 0x01, 0x4e, 0x71,
    0x46, 0x02, 0x46, 0x03, 0x4e, 0x71, 0x46, 0x04, 0x4e, 0x71, 0x46, 0x05,
    0x4e, 0x71, 0x46, 0x06, 0x4e, 0x71,
  ]);
  const disassembler = new CS.CAPSTONE(CS.ARCH_M68K, CS.MODE_M68K_020);
  disassembler.option(CS.OPT_DETAIL, true);
  const insns = disassembler.disasm(buffer, 0x1000);

  expect(
    insns.map(({ id, address, size, mnemonic, op_str, bytes }) => ({
      id,
      address,
      size,
      mnemonic,
      op_str,
      bytes,
    })),
  ).toEqual([
    {
      id: 291,
      address: 4096,
      size: 4,
      mnemonic: 'nbcd.b',
      op_str: '$34(a2, d1.w)',
      bytes: new Uint8Array([72, 50, 18, 52]),
    },
    {
      id: 5,
      address: 4100,
      size: 4,
      mnemonic: 'addq.w',
      op_str: '#$3, $d22a.w',
      bytes: new Uint8Array([86, 120, 210, 42]),
    },
    {
      id: 0,
      address: 4104,
      size: 2,
      mnemonic: 'dc.w',
      op_str: '$abcd',
      bytes: new Uint8Array([171, 205]),
    },
    {
      id: 5,
      address: 4106,
      size: 2,
      mnemonic: 'addq.b',
      op_str: '#$2, d3',
      bytes: new Uint8Array([84, 3]),
    },
    {
      id: 297,
      address: 4108,
      size: 4,
      mnemonic: 'ori.b',
      op_str: '#$38, d0',
      bytes: new Uint8Array([0, 0, 76, 56]),
    },
    {
      id: 297,
      address: 4112,
      size: 4,
      mnemonic: 'ori.b',
      op_str: '#$a, d1',
      bytes: new Uint8Array([0, 1, 76, 10]),
    },
    {
      id: 297,
      address: 4116,
      size: 4,
      mnemonic: 'ori.b',
      op_str: '#$2c, d2',
      bytes: new Uint8Array([0, 2, 208, 44]),
    },
  ]);

  disassembler.close();
});
