#include "assoclist_bug_demo.h"
#include "assoc_list.h"
#include "nwk_globals.h"
#include "ti_zstack_config.h"

/*
 * Demonstrates the bug in assoc_list.o (libZStack_nwk_all.a) using the real
 * library functions: AssocAddNew (registration) and AssocCount (counting).
 *
 * Requires NWK_MAX_DEVICE_LIST >= 255 in ti_zstack_config.h
 * (set to 300 for this demonstration — see comment in that file).
 *
 * With NWK_MAX_DEVICE_LIST = 300:
 *   gNWK_MAX_DEVICE_LIST = 301 (uint16_t) → little-endian: [0x2D, 0x01]
 *   AssocAddNew reads gNWK_MAX_DEVICE_LIST as uint8_t → gets 0x2D = 45 → rejects entries after slot 45
 *   AssocCount  reads gNWK_MAX_DEVICE_LIST as uint8_t → gets 0x2D = 45 → iterates only 45 entries
 *
 * Inspect via debugger after assoclistBugDemoRun() returns:
 *   demo_expected   → 300  (NWK_MAX_DEVICE_LIST as configured)
 *   demo_add_ok     → 45   (AssocAddNew returned NULL for every call after slot 45)
 *   demo_count_ok   → 45   (AssocCount only iterates 45 entries)
 *   demo_bug_proven → 1    (0 = ok, 1 = bug confirmed)
 */

#define DEMO_ADD_COUNT  NWK_MAX_DEVICE_LIST   /* attempts to fill the table up to the configured limit (300) */

volatile uint16_t demo_expected   = DEMO_ADD_COUNT;
volatile uint16_t demo_add_ok     = 0;
volatile uint16_t demo_count_ok   = 0;
volatile uint8_t  demo_bug_proven = 0;

void assoclistBugDemoRun(void)
{
  uint8_t  fake_ext[8] = {0xDE, 0xAD, 0xBE, 0xEF, 0x00, 0x00, 0x00, 0x00};

  AssocReset();  /* start with a clean table */

  for (uint16_t i = 1; i <= DEMO_ADD_COUNT; i++)
  {
    fake_ext[6] = (uint8_t)(i >> 8);
    fake_ext[7] = (uint8_t)(i & 0xFF);
    if (AssocAddNew(i, fake_ext, CHILD_RFD) != NULL)
      demo_add_ok++;
  }

  demo_count_ok   = AssocCount(CHILD_RFD, CHILD_FFD_RX_IDLE);
  demo_bug_proven = (demo_add_ok != demo_expected);

  AssocReset();  /* restore clean state */
}
