set(COMPONENT_SRCS
"main.c"
"buffer.c"
"comm_uart.c"
"comm_usb.c"
"comm_can.c"
"comm_ble.c"
"comm_wifi.c"
"hub_creds.c"
"hub_policy.c"
"ota_rollback.c"
"crash_ring.c"
"crash_collect.c"
"crash_seal.c"
"packet.c"
"pkt_dec.c"
"crc.c"
"commands.c"
"log_ring.c"
"wifi_nets.c"
"wifi_pick.c"
"conf_custom.c"
"terminal.c"
"mempools.c"
"log.c"
"adc.c"
"ublox.c"
"nmea.c"
"utils.c"
"flash_helper.c"
"script/pkg_table.c"
"rb.c"
"bms.c"
"log_comm.c"
"digital_filter.c"
"modem/modem.c"
"modem/modem_esp.c"
"wifi/script_tcp.c"

"config/confsrc.c"
"hwconf/hw.c"

"lispif.c"
"lispif_c_lib.c"
"lispif_events.c"
"lbm_vesc_utils.c"
"lispif_vesc_extensions.c"
"lbm_color_extensions.c"
"display/color_core.c"
"lispBM/src/env.c"
"lispBM/src/fundamental.c"
"lispBM/src/heap.c"
"lispBM/src/lbm_memory.c"
"lispBM/src/print.c"
"lispBM/src/stack.c"
"lispBM/src/symrepr.c"
"lispBM/src/tokpar.c"
"lispBM/src/extensions.c"
"lispBM/src/lispbm.c"
"lispBM/src/eval_cps.c"
"lispBM/platform/freertos/src/platform_mutex.c"
"lispBM/platform/freertos/src/platform_timestamp.c"
"lispBM/src/lbm_channel.c"
"lispBM/src/lbm_c_interop.c"
"lispBM/src/lbm_custom_type.c"
"lispBM/src/lbm_flat_value.c"
"lispBM/src/lbm_prof.c"
"lispBM/src/lbm_defrag_mem.c"
"lispBM/src/lbm_image.c"
"lispBM/src/extensions/array_extensions.c"
"lispBM/src/extensions/math_extensions.c"
"lispBM/src/extensions/string_extensions.c"
"lispBM/src/extensions/display_extensions.c"
"lispBM/src/extensions/mutex_extensions.c"
"lispBM/src/extensions/runtime_extensions.c"
"lispBM/src/extensions/lbm_dyn_lib.c"
"lispBM/src/extensions/ttf_extensions.c"
"lispBM/src/extensions/schrift.c"
"lispBM/src/extensions/ttf_backend.c"
"lispBM/utils/tjpgd.c"
"lispBM/utils/tinygfx.c"

"wifi/lispif_wifi_extensions.c"

"ble/custom_ble.c"

"rgbled/lispif_rgbled_extensions.c"

"touch/lispif_touch_extensions.c"
"touch/touch_core.c"
"touch/touch_cst836u.c"
"touch/touch_axs5106.c"

"display/lispif_disp_extensions.c"
"display/disp_sh8501b.c"
"display/disp_ili9341.c"
"display/disp_ssd1306.c"
"display/disp_st7789.c"
"display/disp_st7789a.c"
"display/disp_ili9488.c"
"display/disp_st7735.c"
"display/disp_ssd1351.c"
"display/disp_icna3306.c"
"display/disp_sh8601.c"
"display/disp_axs15231.c"
"display/disp_gc9a01.c"
"display/disp_jd9853.c"
"display/disp_jd9165.c"
"display/disp_st7701.c"
"display/disp_st7701_rgb.c"
"display/clay_layout.c"
"display/disp_backend.c"
"display/ttf_font.c"

"drivers/bme280/bme280.c"
"drivers/bme280/bme280_if.c"
"drivers/hwi2c.c"
"drivers/hwspi.c"
"drivers/spi_bb.c"
"drivers/enc_as504x.c"
"drivers/imu/imu.c"
"drivers/imu/lsm6ds3.c"
"drivers/imu/ahrs.c"

"lowzip/lowzip.c"
)

# --------------------------------------------------------------------------
# Script engine selection.
#
#   idf.py -DSCRIPT_ENGINE=lua -DHW_NAME="S3 N16R8" build
#
# Default is lisp, which is the configuration everything else in this tree
# expects, and selecting it changes nothing. Choosing lua swaps the whole
# scripting subsystem: LispBM, its VESC extension bindings and the adapter in
# lispif.c come out; Lua, the shared container parser and the adapter in
# main/script/luaif.c go in.
#
# The two adapters implement the same eight entry points, so commands.c,
# comm_can.c and main.c are untouched either way and do not know which
# language the board runs.
#
# A lua build also drops the display, touch, BLE, wifi and rgbled extension
# modules, and the board files that register their own lisp extensions. Those
# are written against the LispBM value ABI, which is the real work in porting
# them -- see tools/script_ext_coverage.py for what is bound so far. Boards
# with no lisp glue of their own build as they are.
set(SCRIPT_ENGINE "lisp" CACHE STRING "Script engine: lisp or lua")
set_property(CACHE SCRIPT_ENGINE PROPERTY STRINGS lisp lua)

if(SCRIPT_ENGINE STREQUAL "lua")
    # Announced only in the real configure pass. IDF also runs this file in
    # cmake script mode to scan requirements, where the -D is not passed, so
    # printing unconditionally reports the wrong engine once per build.
    if(NOT CMAKE_SCRIPT_MODE_FILE)
        message(STATUS "Script engine: Lua (LispBM excluded)")
    endif()

    # Everything written against the LispBM ABI. touch/touch_core.c,
    # touch/touch_cst836u.c and display/color_core.c are deliberately absent:
    # those are engine-neutral and both engines bind to them.
    set(LBM_DEPENDENT
        "lispif.c"
        "lispif_c_lib.c"
        "lispif_events.c"
        "lbm_vesc_utils.c"
        "lispif_vesc_extensions.c"
        "lbm_color_extensions.c"
        "wifi/lispif_wifi_extensions.c"
        "rgbled/lispif_rgbled_extensions.c"
        "touch/lispif_touch_extensions.c"
        "display/lispif_disp_extensions.c"
        "display/clay_layout.c"
    )
    foreach(src ${COMPONENT_SRCS})
        # The lispBM tree itself, and the display drivers, which register
        # their own extensions alongside the driver code.
        # tinygfx and tjpgd sit under lispBM/utils but depend on nothing from
        # the interpreter -- they are the drawing primitives both engines use
        # -- so a lua build keeps them.
        if(src MATCHES "^lispBM/utils/")
            continue()
        endif()
        # The panel drivers are engine-neutral now: their LispBM extension
        # wrappers are guarded, and their callbacks use tinygfx types only.
        if(src MATCHES "^lispBM/")
            list(APPEND LBM_DEPENDENT ${src})
        endif()
    endforeach()

    foreach(src ${LBM_DEPENDENT})
        list(REMOVE_ITEM COMPONENT_SRCS ${src})
    endforeach()

    file(GLOB LUA_CORE_SRCS RELATIVE ${CMAKE_CURRENT_SOURCE_DIR} "lua/*.c")
    list(APPEND COMPONENT_SRCS
        ${LUA_CORE_SRCS}
        "script/script_pack.c"
        "script/script_lua.c"
        "script/lua_vesc_ext.c"
        "script/lua_vesc_io.c"
        "script/lua_vesc_disp.c"
        "script/lua_vesc_disp_load.c"
        "script/lua_vesc_touch.c"
        "script/lua_vesc_bms.c"
        "script/lua_vesc_wifi.c"
        "script/lua_vesc_tcp.c"
        "script/lua_vesc_conf.c"
        "script/lua_vesc_color.c"
        "script/lua_vesc_font.c"
        "lispBM/src/extensions/ttf_backend.c"
        "script/luaif.c"
    )

else()
    if(NOT CMAKE_SCRIPT_MODE_FILE)
        message(STATUS "Script engine: LispBM")
    endif()
    # Several packages per board: the container parser and the package
    # loader, shared with bldc.
    list(APPEND COMPONENT_SRCS
        "script/script_pack.c"
        "script/lbm_pkgs.c"
    )
endif()

if(CONFIG_BT_NIMBLE_ENABLED)
    list(APPEND COMPONENT_SRCS
        "ble/lispif_ble_extensions.c"
    )
endif()

set(COMPONENT_ADD_INCLUDEDIRS
"."
"config"
"lua"
"script"
"lispBM/src/extensions"
"hwconf"
"hwconf/devkits"
"hwconf/trampa"
"hwconf/trampa/bms_rb"
"hwconf/vesc"
"hwconf/vesc/vbms32"
"hwconf/vesc/vdisp_dual"
"hwconf/vesc/scope"
"hwconf/vesc/duet"
"hwconf/vesc/link"
"hwconf/vesc/vdisp_900"
"hwconf/vesc/nanolog"
"hwconf/vesc/vbms16"
"hwconf/vesc/rmcore"
"hwconf/vesc/dash16"
"hwconf/vesc/wcore"
"hwconf/rescue"
"hwconf/avaspark"
"hwconf/vesc/vbms_inf_sat"
"hwconf/vesc/vbms_inf_mas"
"hwconf/seeed"
"hwconf/waveshare/s3_touch_lcd4"
"hwconf/waveshare/s3_sim7670g"
"modem"
"hwconf/waveshare/p4_touch_lcd43"

"lispBM"
"lispBM/include"
"lispBM/platform/freertos/include"
"lispBM/utils"
"display"
"display/clay"
"wifi"
"ble"
"rgbled"
"touch"
"drivers"
"drivers/bme280"
"drivers/imu"
"lowzip"
)

idf_component_register(SRCS ${COMPONENT_SRCS}
    INCLUDE_DIRS ${COMPONENT_ADD_INCLUDEDIRS}
)

if(CONFIG_BT_NIMBLE_ENABLED)
    idf_component_get_property(bt_dir bt COMPONENT_DIR)
    target_include_directories(${COMPONENT_LIB} PRIVATE
        "${bt_dir}/host/nimble/nimble/nimble/host/src")
endif()

if(NOT DEFINED ENV{HW_SRC} AND NOT DEFINED ENV{HW_HEADER})
    idf_build_get_property(hw_file VESC_HW_FILE)
    target_compile_definitions(${COMPONENT_LIB} PRIVATE HW_HEADER="${hw_file}.h" HW_SOURCE="${hw_file}.c")
endif()

# After registration: during IDF's requirements scan this file is run in cmake
# script mode, where add_compile_definitions does not exist, and the scan stops
# at register_component(). Anything using it therefore has to sit below here --
# which is why the LBM_USE_* block further down works.
if(SCRIPT_ENGINE STREQUAL "lua")
    add_compile_definitions(SCRIPT_ENGINE_LUA=1)
else()
    add_compile_definitions(SCRIPT_ENGINE_LISP=1)
endif()

# Bring-up builds for boards whose only reachable port is a USB-to-UART
# bridge. See the BRINGUP_UART block in a board header for what it changes and
# why it is not a shipping configuration.
if(BRINGUP_UART)
    add_compile_definitions(BRINGUP_UART=1)
endif()
if(BRINGUP_CONSOLE)
    add_compile_definitions(BRINGUP_CONSOLE=1)
endif()

# The ESP32-C3's 1600k app slots are full: IDF 6.1 grew the image by ~10 kB,
# Express T was left 224 bytes short of the end, and the 4 MB partition table
# cannot give more without moving the lisp partition, which would erase an
# uploaded script. lispif_vesc_extensions.c is the largest file in the image
# and is reached from LispBM calls rather than from any time-critical loop, so
# it is built for size there: 8.6 kB on Express T. Targets with room keep -O2.
#
# Upstream's BLE HID and long reads (2026-10) then took Express T 704 bytes
# past the end again. The BLE glue joins it: custom_ble.c and its LispBM
# extensions run when a script sets up or uses a BLE service, not in any
# loop that has a deadline.
if(IDF_TARGET STREQUAL "esp32c3")
    set_source_files_properties(lispif_vesc_extensions.c PROPERTIES COMPILE_OPTIONS "-Os")
    set_source_files_properties(ble/custom_ble.c ble/lispif_ble_extensions.c
        PROPERTIES COMPILE_OPTIONS "-Os")
    # Hub friends (2026-10) left 768 bytes. Pairing runs when someone pairs,
    # and the friends' policy is one table lookup per hub packet.
    set_source_files_properties(hub_creds.c hub_policy.c
        PROPERTIES COMPILE_OPTIONS "-Os")
    # WiFi network hopping (2026-10) was 2.9 kB against 200 bytes left. It
    # runs when the station has lost its network, the terminal when someone
    # types at it, crash collection and sealing every few seconds at most or
    # once after a crash, and the OTA rollback check once per boot -- none of
    # them a loop with a deadline. flash_helper.c writes firmware and scripts
    # at the speed the link delivers them. ublox.c parses a GNSS receiver at
    # 5-10 Hz and was there for headroom: without it the image ended 16 bytes
    # short of the slot, which the next change of any kind would overrun.
    set_source_files_properties(wifi_nets.c wifi_pick.c terminal.c
        crash_collect.c crash_seal.c crash_ring.c ota_rollback.c flash_helper.c
        ublox.c
        PROPERTIES COMPILE_OPTIONS "-Os")
    # The CAN receive queue's drop counter (2026-11) took it 16 bytes past
    # the end. main.c runs once at boot, bms.c parses BMS messages a few
    # times a second, and the LispBM WiFi bindings run when a script sets up
    # WiFi.
    set_source_files_properties(main.c bms.c wifi/lispif_wifi_extensions.c
        PROPERTIES COMPILE_OPTIONS "-Os")
    # Script sockets with TLS (2026-11), 4.4 kB against 368 bytes left. They
    # run at the speed of the network, and a script's request rate.
    set_source_files_properties(wifi/script_tcp.c script/lua_vesc_tcp.c
        PROPERTIES COMPILE_OPTIONS "-Os")
    # Several packages per board (2026-11) was 12.8 kB against 368 bytes
    # left. The package table and the commands over it run when something is
    # installed or a script starts; commands.c parses packets at the rate the
    # link delivers them and lispif.c starts and stops the engine and serves
    # the REPL. None of it is in a loop with a deadline.
    set_source_files_properties(script/pkg_table.c script/lbm_pkgs.c
        script/script_pack.c commands.c lispif.c lispif_events.c
        PROPERTIES COMPILE_OPTIONS "-Os")
    # That still left it 6.5 kB over. These run when a script is loaded or
    # printed rather than while it runs: the reader, the image writer, the
    # printer, the native library loader, the decompressor for imports, the
    # dynamic function definitions, the defragmenter and the profiler, plus
    # the RGB LED and GNSS parsers, which run at a few hertz.
    set_source_files_properties(lispBM/src/tokpar.c lispBM/src/lbm_image.c
        lispBM/src/print.c lispBM/src/lbm_prof.c lispBM/src/lbm_defrag_mem.c
        lispBM/src/extensions/lbm_dyn_lib.c lispif_c_lib.c lowzip/lowzip.c
        rgbled/lispif_rgbled_extensions.c nmea.c
        PROPERTIES COMPILE_OPTIONS "-Os")
    # And for headroom: the SD-card logger (rows at tens of hertz), the
    # LispBM touch, colour and display-setup bindings, which set things up
    # rather than draw, and the string functions, which a C3 script uses for
    # messages rather than in a control loop.
    set_source_files_properties(log.c touch/lispif_touch_extensions.c
        lbm_color_extensions.c display/lispif_disp_extensions.c
        lispBM/src/extensions/string_extensions.c
        PROPERTIES COMPILE_OPTIONS "-Os")
endif()

# Clay is ~80 kB of flash and is only usable on a board with a display, so it
# is enabled for the targets with room rather than for everything. The C3 in
# particular has very little app partition left.
if(IDF_TARGET STREQUAL "esp32s3" OR IDF_TARGET STREQUAL "esp32p4")
    add_compile_definitions(HW_USE_CLAY)

    # LispBM's full runtime library, which is what registers mem-size,
    # mem-num-free, mem-longest-free, symtab-size and lbm-heap-state.
    #
    # A script cannot otherwise say anything about the memory it is running
    # out of, and on these boards there is no console to print to either --
    # the only serial port carries the packet protocol. Diagnosing a page
    # thread that failed every clay-layout call with a bare eval_error came
    # down to changing one variable at a time on hardware, because the arena
    # it might have been exhausting was not observable from lisp. It is now.
    #
    # Scoped to the display targets rather than enabled everywhere: it is a
    # handful of extensions, but the C3 counts every byte of app partition.
    add_compile_definitions(FULL_RTS_LIB)
endif()

add_compile_definitions(
    USE_TINYGFX_FONT_ALL
    LBM_USE_DYN_FUNS
    LBM_USE_DYN_MACROS
    LBM_USE_DYN_LOOPS
    LBM_USE_DYN_ARRAYS
    LBM_USE_TIME_QUOTA
    LBM_USE_ERROR_LINENO
    LBM_USE_MACRO_REST_ARGS
)

if((DEFINED ENV{HW_SRC}) OR (DEFINED ENV{HW_HEADER}))
    if(NOT DEFINED ENV{HW_SRC})
        message(FATAL_ERROR "HW_SRC not defined while HW_HEADER is set. You must either set both or none.")
    endif()
    if(NOT DEFINED ENV{HW_HEADER})
        message(FATAL_ERROR "HW_HEADER not defined while HW_SRC is set. You must either set both or none.")
    endif()
    
    message(STATUS "Setting HW_SOURCE=\"$ENV{HW_SRC}\" and HW_HEADER=\"$ENV{HW_HEADER}\" definitions")
    
    add_compile_definitions(
        HW_SOURCE=\"$ENV{HW_SRC}\"
        HW_HEADER=\"$ENV{HW_HEADER}\"
    )
endif()
