# SPDX-FileCopyrightText: 2026 fuddlesworth
# SPDX-License-Identifier: LGPL-2.1-or-later
#
# PhosphorFsLoader — filesystem-backed loader scaffolding with live reload.
#
# A tiny Qt6/C++20 library providing a reusable scaffold for "scan a set
# of directories, register entries with a consumer-supplied registry,
# watch for changes, and rescan on edit". The scaffolding (watcher,
# debounce, parent-watch promotion, file-watch re-arming, rescan-during-
# rescan race guard) lives in `WatchedDirectorySet`. Consumers plug in
# their schema-specific enumeration / parsing / commit logic via
# `IScanStrategy`.
#
# Two specialisations ship with the library out of the box:
#   • `DirectoryLoader` — top-level `*.json` scan with user-wins layering,
#                         dispatch to `IDirectoryLoaderSink`. Used by
#                         CurveLoader, ProfileLoader, etc.
#   • `MetadataPackScanStrategy<Payload>` — per-subdirectory `metadata.json`
#                         scan with SHA-1 change detection. Used by the three
#                         MetadataPackLoader-hosted pack registries.
#
# Loaders with different on-disk shapes (subdirectory layouts, non-JSON
# extensions, custom filename validation) implement `IScanStrategy`
# directly rather than extending `DirectoryLoader`.
#
# Depends on Qt6::Core only. No Gui / Qml / DBus coupling.

# 3.18 floor: the vendored-valijson acquisition below uses file(ARCHIVE_EXTRACT),
# introduced in CMake 3.18.
cmake_minimum_required(VERSION 3.18)

set(PHOSPHORFSLOADER_VERSION "0.1.0")

# The Qt floor this library requires AND advertises in its generated
# PhosphorFsLoaderConfig.cmake. Taken from the top-level QT_MIN_VERSION when built in-tree so
# the two cannot drift, with its own value for a STANDALONE build, where that
# variable does not exist. The fallback is not optional: the Config template
# substitutes this, and an undefined variable expands to nothing and ships a config
# whose find_dependency(Qt6 ...) carries no version floor at all.
if(DEFINED QT_MIN_VERSION)
    set(PHOSPHORFSLOADER_QT_MIN ${QT_MIN_VERSION})
else()
    set(PHOSPHORFSLOADER_QT_MIN "6.10.0")
endif()

if(NOT PROJECT_VERSION)
    project(PhosphorFsLoader VERSION ${PHOSPHORFSLOADER_VERSION} LANGUAGES CXX)
    set(CMAKE_CXX_STANDARD 20)
    set(CMAKE_CXX_STANDARD_REQUIRED ON)
    set(CMAKE_AUTOMOC ON)
endif()

include(GenerateExportHeader)

find_package(Qt6 ${PHOSPHORFSLOADER_QT_MIN} REQUIRED COMPONENTS Core)

# ═══════════════════════════════════════════════════════════════════════════════
# valijson acquisition — header-only JSON Schema (Draft 7) validator.
#
# The archive cmake/PhosphorDependencies.cmake pins by default (from the
# PHOSPHOR_DEPS_ARCHIVES directory in an offline packaging build, downloaded
# with CPM otherwise); system headers opt-in. valijson is header-only and used
# only inside src/schemavalidator.cpp, so it is exposed as a PRIVATE SYSTEM
# include (its warnings stay out of our -Wall/-Wextra build, and it never leaks
# into the public ABI). No add_subdirectory: we want the headers, not
# valijson's own install/export rules.
# ═══════════════════════════════════════════════════════════════════════════════

option(PHOSPHORFSLOADER_USE_SYSTEM_VALIJSON
    "Use system-provided valijson headers instead of the archive cmake/PhosphorDependencies.cmake pins" OFF)

if(PHOSPHORFSLOADER_USE_SYSTEM_VALIJSON)
    find_path(VALIJSON_INCLUDE_DIR
        NAMES valijson/validator.hpp
        DOC "Directory containing valijson/validator.hpp")
    if(NOT VALIJSON_INCLUDE_DIR)
        message(FATAL_ERROR
            "PHOSPHORFSLOADER_USE_SYSTEM_VALIJSON=ON but valijson headers "
            "(valijson/validator.hpp) were not found. Install valijson dev files "
            "or unset the option to use the pinned archive.")
    endif()
else()
    # In-tree the root CMakeLists has already included the module at the top
    # scope, which is where it has to be (it explains why). A standalone
    # configure of this library reaches it by path.
    if(NOT COMMAND phosphor_fetch_dependency)
        include("${CMAKE_CURRENT_SOURCE_DIR}/../../../cmake/PhosphorDependencies.cmake")
    endif()
    phosphor_fetch_dependency(valijson)
    set(_pz_valijson_root "${valijson_SOURCE_DIR}")
    set(VALIJSON_INCLUDE_DIR "${_pz_valijson_root}/include")
endif()

set(phosphorfsloader_SRCS
    src/containedfilereader.cpp
    src/directoryloader.cpp
    src/metadatapackscanstrategy.cpp
    src/schemavalidator.cpp
    src/watcheddirectoryset.cpp
    src/watchedfileset.cpp
)

set(phosphorfsloader_public_HDRS
    include/PhosphorFsLoader/ContainedFileReader.h
    include/PhosphorFsLoader/DirectoryLoader.h
    include/PhosphorFsLoader/FileLimits.h
    include/PhosphorFsLoader/IDirectoryLoaderSink.h
    include/PhosphorFsLoader/IScanStrategy.h
    include/PhosphorFsLoader/JsonEnvelopeValidator.h
    include/PhosphorFsLoader/PackPathGuard.h
    include/PhosphorFsLoader/MetadataPackScanStrategy.h
    include/PhosphorFsLoader/ParsedEntry.h
    include/PhosphorFsLoader/SchemaValidator.h
    include/PhosphorFsLoader/WatchedDirectorySet.h
    include/PhosphorFsLoader/WatchedFileSet.h
)

add_library(PhosphorFsLoader SHARED
    ${phosphorfsloader_public_HDRS}
    ${phosphorfsloader_SRCS}
)

add_library(PhosphorFsLoader::PhosphorFsLoader ALIAS PhosphorFsLoader)

generate_export_header(PhosphorFsLoader
    EXPORT_FILE_NAME ${CMAKE_CURRENT_BINARY_DIR}/PhosphorFsLoader/phosphorfsloader_export.h
    EXPORT_MACRO_NAME PHOSPHORFSLOADER_EXPORT
)

if(NOT DEFINED KDE_INSTALL_INCLUDEDIR)
    include(GNUInstallDirs)
    set(KDE_INSTALL_INCLUDEDIR ${CMAKE_INSTALL_INCLUDEDIR})
    set(KDE_INSTALL_LIBDIR ${CMAKE_INSTALL_LIBDIR})
    # The install(TARGETS) below names a RUNTIME destination too; without this
    # a standalone (non-ECM) configure expands it empty. Matches the sibling
    # fallbacks in phosphor-registry and phosphor-tiles.
    set(KDE_INSTALL_BINDIR ${CMAKE_INSTALL_BINDIR})
endif()

target_include_directories(PhosphorFsLoader
    PUBLIC
        $<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include>
        $<BUILD_INTERFACE:${CMAKE_CURRENT_BINARY_DIR}>
        $<INSTALL_INTERFACE:${KDE_INSTALL_INCLUDEDIR}>
)

target_compile_features(PhosphorFsLoader PUBLIC cxx_std_20)

# valijson headers are a PRIVATE implementation detail of schemavalidator.cpp.
# SYSTEM keeps the project's -Wall/-Wextra/-Wpedantic from flagging the
# third-party headers.
target_include_directories(PhosphorFsLoader SYSTEM PRIVATE "${VALIJSON_INCLUDE_DIR}")

# valijson's schema parser throws on a malformed schema; schemavalidator.cpp
# catches it to fail closed. KDECompilerSettings disables exceptions by
# default (see the -fexceptions override on vendored Luau), so re-enable them
# on just this translation unit. The VALIJSON_USE_EXCEPTIONS define (which tells
# valijson to `throw` rather than abort) is scoped to the SAME TU so the
# throwing macro and the exceptions flag always travel together — a future TU
# that includes a valijson header without this scope compiles under
# -fno-exceptions and would be unable to build the throwing code.
set_source_files_properties(src/schemavalidator.cpp PROPERTIES
    COMPILE_OPTIONS "$<$<OR:$<CXX_COMPILER_ID:GNU>,$<CXX_COMPILER_ID:Clang>>:-fexceptions>"
    COMPILE_DEFINITIONS "VALIJSON_USE_EXCEPTIONS=1")

target_link_libraries(PhosphorFsLoader
    PUBLIC
        Qt6::Core
)

set_target_properties(PhosphorFsLoader PROPERTIES
    VERSION ${PHOSPHORFSLOADER_VERSION}
    SOVERSION 0
)

if(CMAKE_PROJECT_NAME STREQUAL "PhosphorFsLoader" OR BUILD_TESTING)
    enable_testing()
    add_subdirectory(tests)
endif()

if(NOT DEFINED KDE_INSTALL_DATADIR)
    include(GNUInstallDirs)
    set(KDE_INSTALL_DATADIR ${CMAKE_INSTALL_DATAROOTDIR})
endif()

# valijson is BSD-2-Clause (Tristan Penman) and, in the default vendored build,
# its headers are compiled into this library — so its licence notice must
# accompany the distribution. Ship it alongside the app's own licences, next to
# the vendored Luau notice phosphor-scripting installs. The system-valijson
# build uses separately-installed headers that carry their own licence, so skip
# it there. Guarded on the file existing for the same reason as the Luau rule:
# a scope that skips the extraction must not leave an install rule pointing at
# a path that was never created.
if(NOT PHOSPHORFSLOADER_USE_SYSTEM_VALIJSON)
    set(_pz_valijson_license "${_pz_valijson_root}/LICENSE")
    if(EXISTS "${_pz_valijson_license}")
        install(FILES ${_pz_valijson_license}
            DESTINATION ${KDE_INSTALL_DATADIR}/licenses/plasmazones
            RENAME LICENSE.valijson)
    endif()
endif()

install(TARGETS PhosphorFsLoader
    EXPORT PhosphorFsLoaderTargets
    RUNTIME DESTINATION ${KDE_INSTALL_BINDIR}
    LIBRARY DESTINATION ${KDE_INSTALL_LIBDIR}
    ARCHIVE DESTINATION ${KDE_INSTALL_LIBDIR}
)

install(FILES ${phosphorfsloader_public_HDRS}
    DESTINATION ${KDE_INSTALL_INCLUDEDIR}/PhosphorFsLoader
)
install(FILES ${CMAKE_CURRENT_BINARY_DIR}/PhosphorFsLoader/phosphorfsloader_export.h
    DESTINATION ${KDE_INSTALL_INCLUDEDIR}/PhosphorFsLoader
)

install(EXPORT PhosphorFsLoaderTargets
    FILE PhosphorFsLoaderTargets.cmake
    NAMESPACE PhosphorFsLoader::
    DESTINATION ${KDE_INSTALL_LIBDIR}/cmake/PhosphorFsLoader
)

include(CMakePackageConfigHelpers)
configure_package_config_file(
    "${CMAKE_CURRENT_SOURCE_DIR}/PhosphorFsLoaderConfig.cmake.in"
    "${CMAKE_CURRENT_BINARY_DIR}/PhosphorFsLoaderConfig.cmake"
    INSTALL_DESTINATION ${KDE_INSTALL_LIBDIR}/cmake/PhosphorFsLoader
)
write_basic_package_version_file(
    "${CMAKE_CURRENT_BINARY_DIR}/PhosphorFsLoaderConfigVersion.cmake"
    VERSION ${PHOSPHORFSLOADER_VERSION}
    COMPATIBILITY SameMajorVersion
)
install(FILES
    "${CMAKE_CURRENT_BINARY_DIR}/PhosphorFsLoaderConfig.cmake"
    "${CMAKE_CURRENT_BINARY_DIR}/PhosphorFsLoaderConfigVersion.cmake"
    DESTINATION ${KDE_INSTALL_LIBDIR}/cmake/PhosphorFsLoader
)
