if(NOT DEFINED PANO_CLI)
    message(FATAL_ERROR "PANO_CLI must be set")
endif()

if(NOT DEFINED OUTPUT_PATH)
    message(FATAL_ERROR "OUTPUT_PATH must be set")
endif()

get_filename_component(output_dir "${OUTPUT_PATH}" DIRECTORY)
file(MAKE_DIRECTORY "${output_dir}")
file(REMOVE "${OUTPUT_PATH}")

execute_process(
    COMMAND "${PANO_CLI}" export-image
        --path "${OUTPUT_PATH}"
        --width 3
        --height 2
    RESULT_VARIABLE export_result
    OUTPUT_VARIABLE export_output
    ERROR_VARIABLE export_error)

if(NOT export_result EQUAL 0)
    message(FATAL_ERROR "export-image failed: ${export_output}${export_error}")
endif()

string(FIND "${export_output}" "\"command\":\"export-image\"" export_command_index)
string(FIND "${export_output}" "\"format\":\"png\"" export_format_index)
string(FIND "${export_output}" "\"width\":3" export_width_index)
string(FIND "${export_output}" "\"height\":2" export_height_index)
string(FIND "${export_output}" "\"bytes\":24" export_bytes_index)
if(export_command_index LESS 0
    OR export_format_index LESS 0
    OR export_width_index LESS 0
    OR export_height_index LESS 0
    OR export_bytes_index LESS 0)
    message(FATAL_ERROR "export-image output did not contain expected summary: ${export_output}")
endif()

if(NOT EXISTS "${OUTPUT_PATH}")
    message(FATAL_ERROR "export-image did not create ${OUTPUT_PATH}")
endif()

execute_process(
    COMMAND "${PANO_CLI}" import-image
        --path "${OUTPUT_PATH}"
        --document-width 16
        --document-height 8
        --face 1
        --x 2
        --y 3
    RESULT_VARIABLE import_result
    OUTPUT_VARIABLE import_output
    ERROR_VARIABLE import_error)

if(NOT import_result EQUAL 0)
    message(FATAL_ERROR "import-image failed after export-image: ${import_output}${import_error}")
endif()

string(FIND "${import_output}" "\"command\":\"import-image\"" import_command_index)
string(FIND "${import_output}" "\"image\":{\"format\":\"png\",\"width\":3,\"height\":2,\"bytes\":24}" import_image_index)
string(FIND "${import_output}" "\"document\":{\"width\":16,\"height\":8,\"layers\":1,\"frames\":1,\"facePayloads\":1}" import_document_index)
string(FIND "${import_output}" "\"payload\":{\"face\":1,\"x\":2,\"y\":3,\"width\":3,\"height\":2,\"bytes\":24}" import_payload_index)
if(import_command_index LESS 0
    OR import_image_index LESS 0
    OR import_document_index LESS 0
    OR import_payload_index LESS 0)
    message(FATAL_ERROR "import-image output did not contain expected exported-image summary: ${import_output}")
endif()
