#!/usr/bin/env nu
# reflection-request.nu - Handle ecosystem.reflection.request events
# Triggers mode execution based on incoming event payload

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

  if ($mode_id | is-empty) {
    error make { msg: "reflection-request: missing mode_id in payload" }
  }

  let cyan = (ansi cyan)
  let reset = (ansi reset)
  print $"  $cyan[reflection-request]$reset Executing mode: ($mode_id)"

  # Set project context for the mode execution
  let exec_result = (do {
    # Switch to project directory if specified
    if ($project | path exists) and ($project | is-dir) {
      cd $project
    }

    # Import and execute modes module - run-mode executes a mode by id
    use ../nulib/modes.nu *
    run-mode $mode_id
  } | complete)

  if $exec_result.exit_code == 0 {
    let green = (ansi green)
    print $"  $green✓$reset Mode completed: ($mode_id)"
  } else {
    let err = ($exec_result.stderr? | default "unknown error")
    error make { msg: $"Mode execution failed for ($mode_id): $err" }
  }
}
