#!/usr/bin/env nu
# reflection/hooks/git-event.nu — called by git post-merge and post-checkout hooks.
#
# For jj repos, this hook is never installed (jj has no hook system).
# The jjw wrapper calls `on-vcs-event` directly after relevant jj operations.

# Core event handler — callable from both the git hook and the jjw wrapper.
#
# Triggers: mode detection, project-context regeneration, daemon sync.
# Never fails the calling operation — all steps are best-effort.
export def "on-vcs-event" [event_type: string = ""]: nothing -> nothing {
    let ontoref_root = ($env.ONTOREF_ROOT? | default "")
    if ($ontoref_root | is-empty) { return }

    let wrapper = $"($ontoref_root)/ontoref"
    if not ($wrapper | path exists) { return }

    # Trigger mode detection + transition. Sync runs inside on-enter-daemon if mode changed.
    do { ^nu $wrapper mode-detect } | complete | null

    # Regenerate static project context for Claude Code sessions.
    let context_file = $"($ontoref_root)/.claude/project-context.md"
    if ($context_file | path parent | path exists) {
        let r = (do { ^nu $wrapper describe project --fmt text } | complete)
        if $r.exit_code == 0 {
            $r.stdout | save --force $context_file
        }
    }

    # If daemon mode is active, push ontology for current VCS event.
    let lock_file = $"($ontoref_root)/.ontoref/mode.lock"
    if not ($lock_file | path exists) { return }

    let lock = (
        do { open $lock_file | from json } | complete
        | get -o stdout
        | default { mode: "local" }
    )

    if $lock.mode == "daemon" {
        let store = $"($ontoref_root)/reflection/modules/store.nu"
        let r = (do { ^nu -c $"use ($store) *; store sync-push" } | complete)
        if $r.exit_code == 0 {
            print $"  (ansi green)ontoref(ansi reset) ontology synced to daemon"
        }
    }
}

# Git hook entry point — called by post-merge / post-checkout.
def main [event: string = ""]: nothing -> nothing {
    on-vcs-event $event
}
