# Copyright (c) 2026 ttldtor.
# SPDX-License-Identifier: BSL-1.0
cmake_minimum_required(VERSION 3.24)

# Script-mode help must not validate paths, discover tools or create artifacts.
if(HELP)
  message([=[Usage: cmake -DHELP=ON -P tools/quality/readability.cmake
       cmake -DBUILD_DIR=<build> "-DFILES=<a.cpp;b.cpp>" -DOUTPUT_DIR=<new-dir> [options] -P tools/quality/readability.cmake
Collect clang-tidy cognitive-complexity observations and provenance.
Required (no defaults):
  BUILD_DIR       Build directory with nonempty compile_commands.json.
  FILES           Semicolon-separated existing source files in the database.
  OUTPUT_DIR      Fresh evidence directory; existing paths are never overwritten.
Optional:
  CLANG_TIDY      Executable path; default: find clang-tidy on PATH.
  TIMEOUT_SECONDS=120  Positive integer timeout per clang-tidy invocation.
  HEADERS        Semicolon-separated existing headers included in provenance.
  EXTRA_ARGS     Semicolon-separated compiler arguments passed as --extra-arg.
  ENABLE_FUNCTION_SIZE=OFF  Also collect readability-function-size observations.
  ENABLE_MAGIC_NUMBERS=OFF  Also collect readability-magic-numbers observations.
  HELP=OFF       ON prints usage and returns before input validation or writes.
Requires CMake >=3.24 and a compatible clang-tidy with the selected checks.
Relative paths resolve from the invocation working directory. Quote CMake lists.
Effects: runs clang-tidy, creates OUTPUT_DIR with raw output, configuration,
source/header/database hashes, summary and status.json. May leave failure evidence.
Exit 0 on completed observations/help; nonzero for NOT_RUN or tool failures.
Observations do not impose a universal cognitive-complexity acceptance threshold.
Example: cmake -DBUILD_DIR=build -DFILES=src/input.cpp -DOUTPUT_DIR=observations/new -P tools/quality/readability.cmake
]=])
  return()
endif()

function(jsonQuote output value)
  string(REPLACE "\\" "\\\\" text "${value}")
  string(REPLACE "\"" "\\\"" text "${text}")
  string(REPLACE "\n" "\\n" text "${text}")
  string(REPLACE "\r" "\\r" text "${text}")
  string(REPLACE "\t" "\\t" text "${text}")
  set(${output} "\"${text}\"" PARENT_SCOPE)
endfunction()

function(escapePathRegex output path)
  file(TO_CMAKE_PATH "${path}" escaped)
  foreach(character "." "+" "*" "?" "^" "$" "(" ")" "[" "]" "{" "}" "|")
    string(REPLACE "${character}" "\\${character}" escaped "${escaped}")
  endforeach()
  string(REPLACE "/" "[/\\\\]" escaped "${escaped}")
  set(${output} "${escaped}" PARENT_SCOPE)
endfunction()

if(NOT DEFINED OUTPUT_DIR OR OUTPUT_DIR STREQUAL "")
  message(FATAL_ERROR "NOT_RUN: OUTPUT_DIR is required")
endif()
get_filename_component(OUTPUT_DIR "${OUTPUT_DIR}" ABSOLUTE)
if(EXISTS "${OUTPUT_DIR}")
  message(FATAL_ERROR "NOT_RUN: refusing to overwrite OUTPUT_DIR: ${OUTPUT_DIR}")
endif()
file(MAKE_DIRECTORY "${OUTPUT_DIR}")

function(stopReadability status reason)
  jsonQuote(reasonJson "${reason}")
  file(WRITE "${OUTPUT_DIR}/status.json"
    "{\"schema\":1,\"status\":\"${status}\",\"reason\":${reasonJson}}\n")
  message(FATAL_ERROR "${status}: ${reason}")
endfunction()

foreach(required BUILD_DIR FILES)
  if(NOT DEFINED ${required} OR "${${required}}" STREQUAL "")
    stopReadability(NOT_RUN "${required} is required")
  endif()
endforeach()
get_filename_component(BUILD_DIR "${BUILD_DIR}" ABSOLUTE)
set(database "${BUILD_DIR}/compile_commands.json")
if(NOT EXISTS "${database}")
  stopReadability(NOT_RUN "compile_commands.json is missing: ${database}")
endif()
file(READ "${database}" commands)
string(JSON commandCount ERROR_VARIABLE jsonError LENGTH "${commands}")
if(NOT jsonError STREQUAL "NOTFOUND" OR commandCount EQUAL 0)
  stopReadability(NOT_RUN "invalid or empty compilation database: ${jsonError}")
endif()
file(SHA256 "${database}" databaseHash)
file(WRITE "${OUTPUT_DIR}/compilation-database.sha256" "${databaseHash}\n")

if(NOT DEFINED TIMEOUT_SECONDS)
  set(TIMEOUT_SECONDS 120)
endif()
if(NOT TIMEOUT_SECONDS MATCHES "^[1-9][0-9]*$")
  stopReadability(NOT_RUN "TIMEOUT_SECONDS must be a positive integer")
endif()

if(NOT DEFINED CLANG_TIDY)
  find_program(CLANG_TIDY NAMES clang-tidy)
endif()
if(NOT CLANG_TIDY OR NOT EXISTS "${CLANG_TIDY}")
  stopReadability(NOT_RUN "clang-tidy executable is unavailable; supply its absolute CLANG_TIDY path")
endif()
execute_process(COMMAND "${CLANG_TIDY}" --version RESULT_VARIABLE versionResult
  OUTPUT_VARIABLE version ERROR_VARIABLE versionError TIMEOUT ${TIMEOUT_SECONDS})
file(WRITE "${OUTPUT_DIR}/version.txt" "${version}${versionError}")
if(NOT versionResult STREQUAL "0")
  stopReadability(NOT_RUN "clang-tidy --version failed: ${versionResult}")
endif()

set(checks "-*,readability-function-cognitive-complexity")
if(ENABLE_FUNCTION_SIZE)
  string(APPEND checks ",readability-function-size")
endif()
if(ENABLE_MAGIC_NUMBERS)
  string(APPEND checks ",readability-magic-numbers")
endif()
set(config "{\"Checks\":\"${checks}\",\"WarningsAsErrors\":\"\",\"CheckOptions\":{\"readability-function-cognitive-complexity.Threshold\":\"0\",\"readability-function-cognitive-complexity.DescribeBasicIncrements\":\"false\"}}")
file(WRITE "${OUTPUT_DIR}/config.json" "${config}\n")
set(extraArguments)
set(extraArgumentsJson "[]")
set(extraIndex 0)
foreach(argument IN LISTS EXTRA_ARGS)
  list(APPEND extraArguments "--extra-arg=${argument}")
  jsonQuote(argumentJson "${argument}")
  string(JSON extraArgumentsJson SET "${extraArgumentsJson}" ${extraIndex} "${argumentJson}")
  math(EXPR extraIndex "${extraIndex} + 1")
endforeach()
file(WRITE "${OUTPUT_DIR}/extra-args.json" "${extraArgumentsJson}\n")
execute_process(COMMAND "${CLANG_TIDY}" "--config=${config}" --list-checks
  RESULT_VARIABLE checksResult OUTPUT_VARIABLE available ERROR_VARIABLE checksError TIMEOUT ${TIMEOUT_SECONDS})
file(WRITE "${OUTPUT_DIR}/checks.txt" "${available}${checksError}")
if(NOT checksResult STREQUAL "0")
  stopReadability(NOT_RUN "clang-tidy --list-checks failed: ${checksResult}")
endif()
foreach(check IN ITEMS readability-function-cognitive-complexity)
  if(NOT available MATCHES "${check}")
    stopReadability(NOT_RUN "clang-tidy does not support ${check}")
  endif()
endforeach()
if(ENABLE_FUNCTION_SIZE AND NOT available MATCHES "readability-function-size")
  stopReadability(NOT_RUN "clang-tidy does not support readability-function-size")
endif()
if(ENABLE_MAGIC_NUMBERS AND NOT available MATCHES "readability-magic-numbers")
  stopReadability(NOT_RUN "clang-tidy does not support readability-magic-numbers")
endif()

set(sources)
foreach(input IN LISTS FILES)
  if(NOT EXISTS "${input}" OR IS_DIRECTORY "${input}")
    stopReadability(NOT_RUN "source is missing or not a file: ${input}")
  endif()
  file(REAL_PATH "${input}" source)
  list(APPEND sources "${source}")
endforeach()
list(REMOVE_DUPLICATES sources)
list(SORT sources)

set(headers)
foreach(input IN LISTS HEADERS)
  if(NOT EXISTS "${input}" OR IS_DIRECTORY "${input}")
    stopReadability(NOT_RUN "explicit header is missing or not a file: ${input}")
  endif()
  file(REAL_PATH "${input}" header)
  list(APPEND headers "${header}")
endforeach()
list(REMOVE_DUPLICATES headers)
list(SORT headers)
set(headerRecords "[]")
set(headerIndex 0)
foreach(header IN LISTS headers)
  file(SHA256 "${header}" headerHash)
  jsonQuote(headerJson "${header}")
  string(JSON headerRecords SET "${headerRecords}" ${headerIndex}
    "{\"path\":${headerJson},\"sha256\":\"${headerHash}\"}")
  math(EXPR headerIndex "${headerIndex} + 1")
endforeach()
file(WRITE "${OUTPUT_DIR}/headers.json" "${headerRecords}\n")

set(sourceRecords "[]")
set(sourceIndex 0)
set(diagnostics "[]")
set(diagnosticIndex 0)
set(seenDiagnostics)
math(EXPR lastCommand "${commandCount} - 1")
foreach(source IN LISTS sources)
  set(commandFound FALSE)
  foreach(index RANGE 0 ${lastCommand})
    string(JSON commandFile ERROR_VARIABLE fileError GET "${commands}" ${index} file)
    string(JSON commandDirectory ERROR_VARIABLE directoryError GET "${commands}" ${index} directory)
    if(NOT fileError STREQUAL "NOTFOUND" OR NOT directoryError STREQUAL "NOTFOUND")
      stopReadability(NOT_RUN "compilation database entry lacks file/directory")
    endif()
    file(REAL_PATH "${commandFile}" canonicalCommandFile BASE_DIRECTORY "${commandDirectory}")
    if(canonicalCommandFile STREQUAL source)
      set(commandFound TRUE)
      break()
    endif()
  endforeach()
  if(NOT commandFound)
    stopReadability(NOT_RUN "explicit source has no compilation database entry: ${source}")
  endif()

  file(SHA256 "${source}" sourceHash)
  jsonQuote(sourceJson "${source}")
  set(sourceRecord "{\"path\":${sourceJson},\"sha256\":\"${sourceHash}\"}")
  string(JSON sourceRecords SET "${sourceRecords}" ${sourceIndex} "${sourceRecord}")
  file(WRITE "${OUTPUT_DIR}/sources.json" "${sourceRecords}\n")
  set(headerFilter "^$")
  if(headers)
    file(REAL_PATH "${commandDirectory}" commandDirectory)
    get_filename_component(sourceDirectory "${source}" DIRECTORY)
    set(includeDirectories "${sourceDirectory}")
    foreach(header IN LISTS headers)
      get_filename_component(headerDirectory "${header}" DIRECTORY)
      list(APPEND includeDirectories "${headerDirectory}")
    endforeach()
    list(REMOVE_DUPLICATES includeDirectories)
    set(aliases "${headers}")
    foreach(header IN LISTS headers)
      file(RELATIVE_PATH relativeHeader "${commandDirectory}" "${header}")
      list(APPEND aliases "${relativeHeader}" "./${relativeHeader}")
      foreach(includeDirectory IN LISTS includeDirectories)
        file(RELATIVE_PATH relativeDirectory "${commandDirectory}" "${includeDirectory}")
        file(RELATIVE_PATH relativeHeader "${includeDirectory}" "${header}")
        if(relativeDirectory STREQUAL "")
          set(alias "${relativeHeader}")
        else()
          set(alias "${relativeDirectory}/${relativeHeader}")
        endif()
        # Clang filters the file-entry spelling, which can contain uncollapsed '..'.
        list(APPEND aliases "${alias}" "./${alias}" "${commandDirectory}/${alias}")
      endforeach()
    endforeach()
    list(REMOVE_DUPLICATES aliases)
    list(SORT aliases)
    set(patterns)
    foreach(alias IN LISTS aliases)
      file(REAL_PATH "${alias}" aliasCanonical BASE_DIRECTORY "${commandDirectory}")
      if(NOT aliasCanonical IN_LIST headers)
        stopReadability(NOT_RUN "header alias does not resolve to an explicit header: ${alias}")
      endif()
      escapePathRegex(pattern "${alias}")
      list(APPEND patterns "${pattern}")
    endforeach()
    list(JOIN patterns "|" alternatives)
    set(headerFilter "^(${alternatives})$")
  endif()
  file(WRITE "${OUTPUT_DIR}/tu-${sourceIndex}.header-filter.txt" "${headerFilter}\n")
  execute_process(COMMAND "${CLANG_TIDY}" "${source}" -p "${BUILD_DIR}"
    "--config=${config}" "--header-filter=${headerFilter}" "--export-fixes=${OUTPUT_DIR}/tu-${sourceIndex}.yaml"
    ${extraArguments}
    RESULT_VARIABLE result OUTPUT_VARIABLE output ERROR_VARIABLE errors TIMEOUT ${TIMEOUT_SECONDS})
  file(WRITE "${OUTPUT_DIR}/tu-${sourceIndex}.stdout.txt" "${output}")
  file(WRITE "${OUTPUT_DIR}/tu-${sourceIndex}.stderr.txt" "${errors}")
  # Source excerpts can legitimately contain "error:"; only diagnostic severity lines are relevant.
  string(REGEX REPLACE "(^|\n)[ \t]*[0-9]+[ \t]*\\|[^\n]*" "\\1" diagnosticText "${output}\n${errors}")
  string(REGEX MATCH "(^|\n)[^ \t\n][^\n]*:[0-9]+:[0-9]+: (fatal )?error:" compilerDiagnostic "${diagnosticText}")
  if(NOT result STREQUAL "0" OR NOT compilerDiagnostic STREQUAL "")
    stopReadability(FAIL "compiler/tool failure for ${source}: ${result}; see raw TU logs")
  endif()
  file(SHA256 "${source}" finalSourceHash)
  if(NOT finalSourceHash STREQUAL sourceHash)
    stopReadability(FAIL "source changed while clang-tidy was running: ${source}")
  endif()
  # This adapter extracts only the documented diagnostic spelling; raw logs/YAML remain authoritative.
  string(REGEX MATCHALL "[^\n]*warning:[^\n]*has cognitive complexity of [0-9]+[^\n]*" lines "${output}\n${errors}")
  string(REGEX MATCHALL "[^\n]*warning:[^\n]*\\[readability-function-cognitive-complexity\\][^\n]*"
    cognitiveWarnings "${output}\n${errors}")
  list(LENGTH lines parsedCount)
  list(LENGTH cognitiveWarnings warningCount)
  if(NOT parsedCount EQUAL warningCount)
    stopReadability(NOT_RUN "unsupported cognitive diagnostic spelling; see raw TU logs")
  endif()
  foreach(line IN LISTS lines)
    string(REGEX MATCH "^(.+):([0-9]+):([0-9]+): warning:" location "${line}")
    if(location STREQUAL "")
      stopReadability(NOT_RUN "unsupported cognitive diagnostic location: ${line}")
    endif()
    set(locationFile "${CMAKE_MATCH_1}")
    set(locationLine "${CMAKE_MATCH_2}")
    set(locationColumn "${CMAKE_MATCH_3}")
    file(REAL_PATH "${locationFile}" canonicalLocation BASE_DIRECTORY "${commandDirectory}")
    if(NOT canonicalLocation IN_LIST sources AND NOT canonicalLocation IN_LIST headers)
      stopReadability(NOT_RUN "diagnostic location lies outside explicit FILES/HEADERS: ${canonicalLocation}")
    endif()
    string(REGEX MATCH "function '[^']+'" functionText "${line}")
    string(REGEX REPLACE "^function '|'$" "" functionName "${functionText}")
    string(REGEX MATCH "has cognitive complexity of ([0-9]+)" complexityText "${line}")
    set(complexity "${CMAKE_MATCH_1}")
    string(SHA256 diagnosticHash "${canonicalLocation}:${locationLine}:${locationColumn}:${functionName}:${complexity}")
    if(diagnosticHash IN_LIST seenDiagnostics)
      continue()
    endif()
    list(APPEND seenDiagnostics "${diagnosticHash}")
    jsonQuote(lineJson "${line}")
    jsonQuote(functionJson "${functionName}")
    jsonQuote(locationJson "${canonicalLocation}")
    set(diagnostic "{\"translation_unit\":${sourceJson},\"file\":${locationJson},\"line\":${locationLine},\"column\":${locationColumn},\"diagnostic\":${lineJson},\"function\":${functionJson},\"complexity\":${complexity}}")
    string(JSON diagnostics SET "${diagnostics}" ${diagnosticIndex} "${diagnostic}")
    math(EXPR diagnosticIndex "${diagnosticIndex} + 1")
  endforeach()
  math(EXPR sourceIndex "${sourceIndex} + 1")
endforeach()

if(headerIndex GREATER 0)
  math(EXPR lastHeader "${headerIndex} - 1")
  foreach(index RANGE 0 ${lastHeader})
    string(JSON header GET "${headerRecords}" ${index} path)
    string(JSON originalHash GET "${headerRecords}" ${index} sha256)
    file(SHA256 "${header}" finalHeaderHash)
    if(NOT finalHeaderHash STREQUAL originalHash)
      stopReadability(FAIL "explicit header changed during analysis: ${header}")
    endif()
  endforeach()
endif()

file(SHA256 "${database}" finalDatabaseHash)
if(NOT finalDatabaseHash STREQUAL databaseHash)
  stopReadability(FAIL "compilation database changed during analysis")
endif()

file(WRITE "${OUTPUT_DIR}/status.json" "{\"schema\":1,\"status\":\"REPORTED\",\"threshold_role\":\"report_positive_complexity_not_acceptance\",\"cognitive_threshold\":0,\"translation_units\":${sourceIndex},\"explicit_headers\":${headerIndex},\"positive_complexity_diagnostics\":${diagnosticIndex},\"zero_complexity_functions\":null,\"compilation_database_sha256\":\"${databaseHash}\",\"compiler_extra_args\":${extraArgumentsJson},\"sources\":${sourceRecords},\"headers\":${headerRecords},\"diagnostics\":${diagnostics}}\n")
message(STATUS "REPORTED: ${sourceIndex} explicit TUs; ${diagnosticIndex} unique positive-complexity diagnostics; not an acceptance verdict")
