# Nimble build configuration script
# ================================

import strutils, os

# Set the source directory
switch("path", "src")

# --- Memory Management ---
# Use the ORC (Optimized Reference Counting) memory manager for better
# performance and deterministic behavior.
switch("mm", "orc")

# --- Threading Support ---
# Enable multithreading capabilities.
switch("threads", "on")

# --- Feature Flags ---
# Enable SSL support for secure connections.
switch("define", "ssl")

# --- Static Linking Configuration ---
# Check for static build flag
when defined(static):
  echo "🔗 Configuring static linking for minimal binary..."

  # Core static linking flags
  switch("passL", "-static")
  switch("passL", "-static-libgcc")

  # Link against musl libc if available (smaller, cleaner static builds)
  when defined(linux):
    if fileExists("/usr/lib/x86_64-linux-musl/libc.a") or
       fileExists("/usr/lib/musl/lib/libc.a"):
      echo "   Using musl libc for static linking"
      switch("gcc.exe", "musl-gcc")
      switch("gcc.linkerexe", "musl-gcc")

  # Strip symbols for smaller binary
  switch("passL", "-s")

  # Link Time Optimization for better code generation
  switch("passC", "-flto")
  switch("passL", "-flto")

  # Additional optimization flags
  switch("passC", "-ffunction-sections")
  switch("passC", "-fdata-sections")
  switch("passL", "-Wl,--gc-sections")

  # Disable dynamic linking
  switch("dynlibOverride", "ssl")
  switch("dynlibOverride", "crypto")

# --- Build Profiles ---
# The following section defines different build profiles for development
# and release builds. You can select a profile by passing the
# appropriate flags to the Nim compiler (e.g., -d:release).

when isMainModule:
  # Default to a debug build if no profile is specified
  let build_profile = strip(gorge("echo $build_profile"))
  if build_profile == "release":
    # --- Release Build ---
    # Optimized for speed and performance.
    switch("opt", "speed")
    switch("define", "release")
    switch("define", "danger") # Turns off all runtime checks
    switch("warning[ProveInit]", "off")
  else:
    # --- Development Build (default) ---
    # Includes debugging information and enables all runtime checks.
    switch("opt", "none")
    switch("debugger", "native")
