# The terminal component: a pty, a libghostty-vt session and the CUI view that
# draws it. Needs the `cui` target. libghostty-vt's build runs `zig build`, so
# Zig 0.17 must be on PATH. Used by the extension and by tests/c.

# Without a version, ghostty reads it from `git tag --points-at HEAD`. Under
# build/ that is cui-py's checkout, and a tag such as 0.2.0 aborts its build.
set(_zig_flags "-Dversion-string=1.0.0")
# Zig targets the build host's CPU by default, and wheels run elsewhere.
# ghostty already builds generic macOS code; the arch is named for cross builds.
if(APPLE AND CMAKE_OSX_ARCHITECTURES STREQUAL "x86_64")
    list(APPEND _zig_flags "-Dtarget=x86_64-macos")
elseif(APPLE AND CMAKE_OSX_ARCHITECTURES STREQUAL "arm64")
    list(APPEND _zig_flags "-Dtarget=aarch64-macos")
elseif(NOT APPLE)
    list(APPEND _zig_flags "-Dcpu=baseline")
endif()
set(GHOSTTY_ZIG_BUILD_FLAGS "${_zig_flags}" CACHE STRING "Extra zig build flags")
# Offline: -DFETCHCONTENT_SOURCE_DIR_GHOSTTY=/path/to/libghostty-vt-1.0.0
include(FetchContent)
FetchContent_Declare(ghostty
    URL https://release.files.ghostty.org/libghostty-vt/1.0.0/libghostty-vt-1.0.0.tar.gz
    URL_HASH SHA256=4a6ef758be721923e1969e7b81b443dcc92d8dd3fb5a39600c03a8817a753676
    DOWNLOAD_EXTRACT_TIMESTAMP TRUE)
FetchContent_MakeAvailable(ghostty)
set(GHOSTTY_LICENSE "${ghostty_SOURCE_DIR}/LICENSE" PARENT_SCOPE)

set(CUI_DIR "${CMAKE_CURRENT_SOURCE_DIR}/../../thirdparty/cui")
add_library(cuiterm STATIC pty.c session.c term_view.c boxdraw.c cuix.c)
# The headers include "cui.h"; only cuix.c reads CUI's private cui_internal.h.
target_include_directories(cuiterm
    PUBLIC "${CMAKE_CURRENT_SOURCE_DIR}" "${CUI_DIR}/include/cui"
    PRIVATE "${CUI_DIR}/src")
target_compile_options(cuiterm PRIVATE -Wall -Wextra -Wshadow -Wstrict-prototypes)
if(CUI_TEXT_SHAPING)
    target_compile_definitions(cuiterm PRIVATE CUI_TEXT_SHAPING)
endif()
target_link_libraries(cuiterm PUBLIC cui ghostty-vt-static)
if(CMAKE_SYSTEM_NAME STREQUAL "Linux")
    # libghostty-vt calls shm_open, which is in librt before glibc 2.34.
    target_link_libraries(cuiterm PUBLIC rt)
endif()
