/**
 * @file main.c
 * @brief System Example (Enter Boot Mode) with Binho Supernova/Pulsar (Blocking C API)
 *
 * This example demonstrates basic system-level control with CosmicSDK C API.
 *
 * Workflow:
 * 1. Create SDK handle, connect to the adapter, and print host device information.
 * 2. Issue the system command to enter boot mode.
 * 3. Clean up SDK resources.
 */

#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>

#include "CosmicSDK_API_c.h"

#define CHECK_RESULT(op, code) \
  do { \
    if ((code) != SUCCESS) { \
      printf("%s failed. ERROR CODE: %u\n", (op), (unsigned)(code)); \
      exit_code = 1; \
      goto cleanup; \
    } \
  } while (0)

int main(void) {
  int exit_code = 0;
  bool connected = false;
  bool boot_mode_requested = false;
  uint16_t result_code = SUCCESS;
  CosmicSDK_Handle* handle_ptr = CosmicSDK_Create(2000);

  if (handle_ptr == NULL) {
    printf("Could not create CosmicSDK handle\n");
    return 1;
  }

  // Step 1: Create SDK handle, connect to the adapter, and print host device information.
  if (!CosmicSDK_Connect(handle_ptr, NULL)) {
    printf("Could not connect to device\n");
    exit_code = 1;
    goto cleanup;
  }
  connected = true;

  C_DeviceInfo deviceInfoOut;
  result_code = CosmicSDK_GetDeviceInfo(handle_ptr, &deviceInfoOut);
  CHECK_RESULT("GetDeviceInfo", result_code);
  printf("Manufacturer: %.*s\n", (int)deviceInfoOut.manufacturerLength, deviceInfoOut.manufacturer);
  printf("Product Name: %.*s\n", (int)deviceInfoOut.productNameLength, deviceInfoOut.productName);
  printf("Serial Number: %.*s\n", (int)deviceInfoOut.serialNumberLength, deviceInfoOut.serialNumber);
  printf("Firmware Version: %.*s\n", (int)deviceInfoOut.fwVersionLength, deviceInfoOut.fwVersion);
  printf("Hardware Version: %.*s\n", (int)deviceInfoOut.hwVersionLength, deviceInfoOut.hwVersion);

  // Step 2: Issue the system command to enter boot mode.
  result_code = CosmicSDK_EnterBootMode(handle_ptr);
  CHECK_RESULT("EnterBootMode", result_code);
  boot_mode_requested = true;
  printf("Boot mode command sent successfully\n");

  // Step 3: Clean up SDK resources.
cleanup:
  if (connected && !boot_mode_requested) {
    CosmicSDK_Disconnect(handle_ptr);
  }
  CosmicSDK_Destroy(handle_ptr);
  return exit_code;
}
