#!/usr/bin/env nu
# reload.nu - Handle ecosystem.reflection.nushell.reload events
# Reloads configuration and clears caches

export def "handle" [payload: record]: nothing -> nothing {
  let reason = ($payload.reason? | default "explicit request")
  let project = ($payload.project? | default ($env.ONTOREF_PROJECT_ROOT? | default $env.ONTOREF_ROOT))

  let cyan = (ansi cyan)
  let reset = (ansi reset)
  print $"  $cyan[reload]$reset Reloading configuration (reason: $reason)"

  # Clear all environment caches
  $env.NATS_AVAILABLE = ""

  # Validate config syntax
  if ($project | path exists) and ($project | is-dir) {
    let config_path = $project + "/.ontoref/config.ncl"
    if ($config_path | path exists) {
      let gray = (ansi dark_gray)
      print $"  $grayConfig path: ($config_path)$reset"

      let validate_result = (do {
        env NICKEL_IMPORT_PATH=$project
        ^nickel typecheck $config_path
      } | complete)

      if $validate_result.exit_code == 0 {
        let green = (ansi green)
        print $"  $green✓$reset Configuration is valid"
      } else {
        let err = ($validate_result.stderr? | default "syntax error")
        error make { msg: $"Configuration validation failed: $err" }
      }
    }
  }

  let green = (ansi green)
  print $"  $green✓$reset Configuration cache cleared"
  print $"  $grayNote: Env changes apply to current shell only. Next command will reload.$reset"
}
