#!/usr/bin/env nu
# install/hooks/post-commit — ontoref attribution hook.
#
# Installed by: ontoref init  (copies to .git/hooks/post-commit and chmod +x)
# Triggered by: git commit
#
# Purpose: notify the running daemon which NCL files changed in this commit
# so multi-actor coordination UIs can show attribution.
# Silently exits when the daemon is not running or ONTOREF_TOKEN is not set.

let token = ($env.ONTOREF_TOKEN? | default "")
if ($token | is-empty) { exit 0 }

let daemon_url = ($env.ONTOREF_DAEMON_URL? | default "http://127.0.0.1:7891")

# Collect NCL files changed in HEAD.
let changed = (
  do { ^git diff-tree --no-commit-id -r --name-only HEAD } | complete
  | if $in.exit_code == 0 { $in.stdout | lines } else { [] }
  | where { |f| ($f | str ends-with ".ncl") or ($f | str ends-with ".jsonl") }
  | where { |f|
      ($f | str starts-with ".ontoref/ontology/")
      or ($f | str starts-with ".ontoref/adrs/")
      or ($f | str starts-with ".ontoref/reflection/")
      or ($f | str starts-with ".ontoref/catalog/")
      or ($f | str starts-with ".ontology/")
      or ($f | str starts-with "adrs/")
      or ($f | str starts-with "reflection/")
      or ($f | str starts-with "catalog/")
    }
)

if ($changed | is-empty) { exit 0 }

let body = { token: $token, files: $changed } | to json

let result = (
  do {
    ^curl -sf -X POST
      -H "Content-Type: application/json"
      -d $body
      $"($daemon_url)/ontology/changed"
  } | complete
)

if $result.exit_code == 0 {
  print $"  ontoref: attributed ($changed | length) NCL file(s) to actor ($token)"
}
