# Golden-file driver: run one .bas through the interpreter and byte-compare
# stdout against the sibling .txt.
#
# The comparison is on raw bytes, not lines: the reference's print pipeline emits
# a trailing double newline on an error line (basicError builds a string ending
# in \n and hands it to Println, which adds another), and that is part of the
# contract. See TODO.md section 1.8.

if(NOT DEFINED BASIC OR NOT DEFINED CASE)
  message(FATAL_ERROR "golden.cmake requires -DBASIC=<interpreter> -DCASE=<file.bas>")
endif()

string(REGEX REPLACE "\\.bas$" ".txt" EXPECTED "${CASE}")

if(NOT EXISTS "${EXPECTED}")
  message(FATAL_ERROR "No golden output beside ${CASE}")
endif()

execute_process(
  COMMAND "${BASIC}" "${CASE}"
  OUTPUT_VARIABLE actual
  ERROR_VARIABLE  stderr_text
  RESULT_VARIABLE rc
)

if(NOT rc EQUAL 0)
  message(FATAL_ERROR "${CASE}: interpreter exited ${rc}\n${stderr_text}")
endif()

file(READ "${EXPECTED}" expected)

if(NOT actual STREQUAL expected)
  # Write what we got beside the build so a failure can be diffed by hand.
  get_filename_component(_base "${CASE}" NAME)
  set(_dump "${CMAKE_CURRENT_BINARY_DIR}/${_base}.actual")
  file(WRITE "${_dump}" "${actual}")
  message(FATAL_ERROR
    "${CASE}: output does not match ${EXPECTED}\n"
    "--- expected ---\n${expected}\n"
    "--- actual ---\n${actual}\n"
    "(actual written to ${_dump})")
endif()
