#!/usr/bin/env nu
# ontology-changed.nu - Handle ecosystem.ontology.changed events
# Triggers ontology-code synchronization

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

  let cyan = (ansi cyan)
  let reset = (ansi reset)
  print $"  $cyan[ontology-changed]$reset Running synchronization for: ($project)"

  # Execute sync with appropriate flags
  let exec_result = (do {
    # Switch to project directory
    if ($project | path exists) and ($project | is-dir) {
      cd $project
    }

    # Import and execute sync module
    use ../modules/sync.nu *

    # Run scan with appropriate flags based on decision
    match $decision {
      "strict" => { scan --strict },
      "quick" => { scan --quick },
      _ => { scan }
    }
  } | complete)

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