#!/usr/bin/env nu
# ontoref dispatcher — all operations routed from here.
# Invoked by ontoref (alias: onref) after Nushell version is verified and ONTOREF_ACTOR is set.
#
# Business logic lives in reflection/modules/ (domain) and reflection/nulib/ (UI).
# This file only defines `def "main X"` subcommands as thin routing shims.

use ../modules/env.nu *
use ../modules/adr.nu *
use ../modules/forms.nu *
use ../modules/prereqs.nu *
use ../modules/register.nu *
use ../modules/backlog.nu *
use ../modules/config.nu *
use ../modules/sync.nu *
use ../modules/coder.nu *
use ../modules/manifest.nu *
use ../modules/describe.nu *
use ../modules/store.nu *
use ../modules/services.nu *
use ../modules/nats.nu *

use ../nulib/fmt.nu *
use ../nulib/shared.nu *
use ../nulib/help.nu [help-group]
use ../nulib/interactive.nu [missing-target, run-interactive]
use ../nulib/dashboard.nu [run-overview, run-health, run-status]
use ../nulib/modes.nu [list-modes, show-mode, run-modes-interactive, run-mode]
use ../nulib/logger.nu [log-action, log-record, log-show-config, log-query, log-follow]

# ── Helpers ───────────────────────────────────────────────────────────────────

def pick-mode []: nothing -> string {
  let modes = (list-modes)
  if ($modes | is-empty) { print "  No modes found."; return "" }
  # Check if stdin is a TTY via external test command.
  let is_tty = (do { ^test -t 0 } | complete | get exit_code) == 0
  if not $is_tty {
    print ""
    for m in $modes {
      print $"  ($m.id)  (ansi dark_gray)($m.trigger)(ansi reset)"
    }
    print ""
    print $"  (ansi dark_gray)Usage: onref run <mode-id>(ansi reset)"
    return ""
  }
  let ids = ($modes | each { |m| $"($m.id)  (ansi dark_gray)($m.trigger)(ansi reset)" })
  let picked = ($ids | input list $"(ansi cyan_bold)Run mode:(ansi reset) ")
  if ($picked | is-empty) { return "" }
  $picked | split row "  " | first
}

# ── Entry ─────────────────────────────────────────────────────────────────────

def "main" [shortcut?: string] {
  match ($shortcut | default "") {
    "ru" => { main run },
    "f"  => { print "Usage: onref f <term>"; },
    "h" | "help" | "-help" | "--help" => { main help },
    ""   => { show-usage-brief },
    _    => { print $"Unknown command: ($shortcut). Run: onref help" },
  }
}

def show-usage-brief [] {
  let caller = ($env.ONTOREF_CALLER? | default "onref")
  print $"\nUsage: ($caller) [command] [options]\n"
  print $"Use '($caller) help' for available commands\n"
}

def "main help" [group?: string] {
  if ($group | is-not-empty) {
    help-group $group
    return
  }

  let actor = ($env.ONTOREF_ACTOR? | default "developer")
  let cmd   = ($env.ONTOREF_CALLER? | default "./onref")

  let brief = adrs-brief
  let adr_status = $"($brief.accepted)A/($brief.superseded)S/($brief.proposed)P"

  print ""
  fmt-header "ontoref — ecosystem patterns and tooling"
  fmt-sep
  print $"(ansi white_bold)Actor(ansi reset): (ansi cyan)($actor)(ansi reset)  |  (ansi white_bold)Root(ansi reset): (ansi cyan)($env.ONTOREF_ROOT)(ansi reset)"
  print ""

  fmt-section "COMMAND GROUPS"
  print ""
  fmt-cmd $"($cmd) help check" "prerequisites and environment checks"
  fmt-cmd $"($cmd) help form" "interactive forms (new_adr, register, etc.)"
  fmt-cmd $"($cmd) help mode" "operational modes (inspect + execute)"
  fmt-cmd $"($cmd) help adr" $"ADR management  (fmt-badge $"($adr_status)")"
  fmt-cmd $"($cmd) help register" "record changes → CHANGELOG + ADR + ontology"
  fmt-cmd $"($cmd) help backlog" "roadmap, items, promotions"
  fmt-cmd $"($cmd) help config" "sealed config profiles, drift, rollback"
  fmt-cmd $"($cmd) help sync" "ontology↔code sync, drift detection, proposals"
  fmt-cmd $"($cmd) help coder" ".coder/ process memory: record, log, triage, publish"
  fmt-cmd $"($cmd) help manifest" "operational modes, publication services, layers"
  fmt-cmd $"($cmd) help describe" "project self-knowledge: what, how, why, impact"
  fmt-cmd $"($cmd) help log" "action audit trail, follow, filter"
  print ""

  fmt-section "QUICK REFERENCE"
  print ""
  fmt-cmd $"($cmd) init" "run actor-configured init mode (from actor_init in config)"
  fmt-cmd $"($cmd) run <mode-id>" "execute a mode (shortcut for mode run)"
  fmt-cmd $"($cmd) find <term>" "search ontology: selector, detail, connections, usage"
  fmt-cmd $"($cmd) about" "project identity and summary"
  fmt-cmd $"($cmd) diagram" "terminal box diagram of project architecture"
  fmt-cmd $"($cmd) overview" "single-screen project snapshot: identity, crates, health"
  fmt-cmd $"($cmd) health" "quick health bar (use --full for deep audit)"
  fmt-cmd $"($cmd) status" "project dashboard: health, state, recent activity"
  fmt-cmd $"($cmd) nats" "NATS event system (status, listen, emit)"
  fmt-cmd $"($cmd) services" "daemon lifecycle (start, stop, restart, status, health)"
  fmt-cmd $"($cmd) check" "run prerequisite checks"
  fmt-cmd $"($cmd) adr list" "list ADRs with status"
  fmt-cmd $"($cmd) constraint" "active Hard constraints"
  fmt-cmd $"($cmd) backlog roadmap" "state dimensions + open items"
  fmt-cmd $"($cmd) config audit" "verify all profiles"
  fmt-cmd $"($cmd) log --tail 10 -t" "last 10 actions with timestamps"
  print ""

  fmt-section "ALIASES"
  print ""
  print $"  (ansi cyan)ad(ansi reset)  → adr           (ansi cyan)d(ansi reset)   → describe      (ansi cyan)ck(ansi reset)  → check        (ansi cyan)con(ansi reset) → constraint"
  print $"  (ansi cyan)rg(ansi reset)  → register      (ansi cyan)bkl(ansi reset) → backlog       (ansi cyan)cfg(ansi reset) → config       (ansi cyan)cod(ansi reset) → coder"
  print $"  (ansi cyan)mf(ansi reset)  → manifest      (ansi cyan)dg(ansi reset)  → diagram       (ansi cyan)md(ansi reset)  → mode         (ansi cyan)st(ansi reset)  → status"
  print $"  (ansi cyan)fm(ansi reset)  → form          (ansi cyan)f(ansi reset)   → find          (ansi cyan)ru(ansi reset)  → run \(mode\)  (ansi cyan)sv(ansi reset)  → services"
  print $"  (ansi cyan)nv(ansi reset)  → nats"
  print ""
  print $"  (ansi dark_gray)Tip: any group accepts(ansi reset) (ansi cyan)h(ansi reset) (ansi dark_gray)for help,(ansi reset) (ansi cyan)?(ansi reset) (ansi dark_gray)for interactive selector, or bare for picker(ansi reset)"
  print ""
}

# ── Check / Forms ─────────────────────────────────────────────────────────────

def "main check" [--context: string = "", --form: string = "", --severity: string = "", --json] {
  log-action "check" "read"
  if $json {
    prereqs check --context $context --form $form --severity $severity --json
  } else {
    prereqs check --context $context --form $form --severity $severity
  }
}

def "main form" [action?: string] { missing-target "form" $action }
def "main form help" [] { help-group "form" }
def "main form run" [name: string, --backend: string = "cli"] {
  log-action $"form run ($name)" "interactive"
  form run $name --backend $backend
}
def "main form list" [] {
  log-action "form list" "read"
  print ""
  for f in (forms list) {
    print $"  ($f.name)"
    print $"    ($f.description)"
    print $"    Agent: nickel-export reflection/forms/($f.name).ncl | get elements | where type != \"section_header\""
    print ""
  }
}
def "main form ls" [] { log-action "form list" "read"; forms list }

# ── Modes ─────────────────────────────────────────────────────────────────────

def "main mode" [action?: string] { missing-target "mode" $action }
def "main mode help" [] { help-group "mode" }
def "main mode list" [--fmt (-f): string = ""] {
  let modes = (list-modes)

  log-action "mode list" "read"
  let f = (resolve-fmt $fmt [text table json yaml toml])
  match $f {
    "json" => { print ($modes | to json) },
    "yaml" => { print ($modes | to yaml) },
    "toml" => { print ({ modes: $modes } | to toml) },
    "table" => { print ($modes | table --expand) },
    _ => {
      print ""
      for m in $modes {
        print $"  ($m.id)"
        print $"    Trigger: ($m.trigger)"
        if $m.steps > 0 { print $"    Steps: ($m.steps)" }
        print ""
      }
    },
  }
}
def "main mode select" [] {
  let modes = (list-modes)
  run-modes-interactive $modes
}
def "main mode show" [id: string, --fmt (-f): string = ""] {
  log-action $"mode show ($id)" "read"
  let actor = ($env.ONTOREF_ACTOR? | default "developer")
  let f = if ($fmt | is-not-empty) { $fmt } else if $actor == "agent" { "json" } else { "md" }
  show-mode $id $f
}

def "main mode run" [id: string, --dry-run (-n), --yes (-y)] {
  log-action $"mode run ($id)" "write"
  run-mode $id --dry-run=$dry_run --yes=$yes
}

# ── ADR ───────────────────────────────────────────────────────────────────────

def "main adr" [action?: string] { missing-target "adr" $action }
def "main adr help" [] { help-group "adr" }
def "main adr list" [--fmt (-f): string = ""] {
  log-action "adr list" "read"
  let f = (resolve-fmt $fmt [table md json yaml toml])
  adr list --fmt $f
}
def "main adr validate" [] { log-action "adr validate" "read"; adr validate }
def "main adr accept" [id: string] { log-action $"adr accept ($id)" "write"; adr accept $id }
def "main adr show" [id?: string, --interactive (-i), --fmt (-f): string = ""] {
  log-action $"adr show ($id | default '?')" "read"
  let f = (resolve-fmt $fmt [md table json yaml toml])
  if $interactive { adr show --interactive --fmt $f } else { adr show $id --fmt $f }
}
def "main adr l" [--fmt (-f): string = ""] { main adr list --fmt $fmt }
def "main adr v" [] { main adr validate }
def "main adr s" [id?: string, --fmt (-f): string = ""] { main adr show $id --fmt $fmt }

# ── Constraints / Register ───────────────────────────────────────────────────

def "main constraint" [--fmt (-f): string = ""] {
  log-action "constraint" "read"
  let f = (resolve-fmt $fmt [table md json yaml toml])
  constraints --fmt $f
}

def "main register" [--backend: string = "cli"] { log-action "register" "write"; register run --backend $backend }

# ── Backlog ───────────────────────────────────────────────────────────────────

def "main backlog" [action?: string] { missing-target "backlog" $action }
def "main backlog help" [] { help-group "backlog" }
def "main backlog roadmap" [] { log-action "backlog roadmap" "read"; backlog roadmap }
def "main backlog list" [--status: string = "", --kind: string = "", --fmt (-f): string = ""] {
  log-action "backlog list" "read"
  let f = (resolve-fmt $fmt [table md json yaml toml])
  backlog list --status $status --kind $kind --fmt $f
}
def "main backlog show" [id: string] { log-action $"backlog show ($id)" "read"; backlog show $id }
def "main backlog add" [title: string, --kind: string = "Todo", --priority: string = "Medium", --detail: string = "", --dim: string = "", --adr: string = "", --mode: string = ""] {
  log-action $"backlog add ($title)" "write"
  backlog add $title --kind $kind --priority $priority --detail $detail --dim $dim --adr $adr --mode $mode
}
def "main backlog done"   [id: string] { log-action $"backlog done ($id)" "write"; backlog done $id }
def "main backlog cancel" [id: string] { log-action $"backlog cancel ($id)" "write"; backlog cancel $id }
def "main backlog promote" [id: string] { log-action $"backlog promote ($id)" "write"; backlog promote $id }

# ── Config ────────────────────────────────────────────────────────────────────

def "main config" [action?: string] { missing-target "config" $action }
def "main config help" [] { help-group "config" }
def "main config show" [profile: string, --fmt (-f): string = ""] {
  log-action $"config show ($profile)" "read"
  let f = (resolve-fmt $fmt [table json yaml toml])
  config show $profile --fmt $f
}
def "main config history" [profile: string, --fmt (-f): string = ""] {
  log-action $"config history ($profile)" "read"
  let f = (resolve-fmt $fmt [table json yaml toml])
  config history $profile --fmt $f
}
def "main config diff" [profile: string, from_id: string, to_id: string] { log-action $"config diff ($profile)" "read"; config diff $profile $from_id $to_id }
def "main config verify" [profile: string] { log-action $"config verify ($profile)" "read"; config verify $profile }
def "main config audit" [] { log-action "config audit" "read"; config audit }
def "main config apply" [profile: string, --adr: string = "", --pr: string = "", --bug: string = "", --note: string = ""] {
  log-action $"config apply ($profile)" "write"
  config apply $profile --adr $adr --pr $pr --bug $bug --note $note
}
def "main config rollback" [profile: string, to_id: string, --adr: string = "", --note: string = ""] {
  log-action $"config rollback ($profile) ($to_id)" "write"
  config rollback $profile $to_id --adr $adr --note $note
}

# ── Sync ──────────────────────────────────────────────────────────────────────

def "main sync" [action?: string] { missing-target "sync" $action }
def "main sync help" [] { help-group "sync" }
def "main sync scan" [--level: string = "auto"] { log-action "sync scan" "read"; sync scan --level $level }
def "main sync diff" [--quick] { log-action "sync diff" "read"; if $quick { sync diff --quick } else { sync diff } }
def "main sync propose" [] { log-action "sync propose" "read"; sync propose }
def "main sync apply" [] { log-action "sync apply" "write"; sync apply }
def "main sync state" [] { log-action "sync state" "read"; sync state }
def "main sync audit" [--fmt (-f): string = "", --strict, --quick] {
  log-action "sync audit" "read"
  let f = (resolve-fmt $fmt [text json])
  sync audit --fmt $f --strict=$strict --quick=$quick
}
def "main sync watch" [] { log-action "sync watch" "read"; sync watch }

# ── Coder ─────────────────────────────────────────────────────────────────────

def "main coder" [action?: string] { missing-target "coder" $action }
def "main coder help" [] { help-group "coder" }
def "main coder authors" [] { log-action "coder authors" "read"; coder authors }
def "main coder init" [author: string, --actor: string = "Human", --model: string = ""] {
  log-action $"coder init ($author)" "write"
  coder init $author --actor $actor --model $model
}
def "main coder record" [
  author: string, content: string,
  --kind (-k): string = "info", --category (-c): string = "", --title (-t): string,
  --tags: list<string> = [], --relates_to: list<string> = [],
  --trigger: string = "", --files_touched: list<string> = [],
  --domain (-d): string = "", --reusable (-r),
] {
  log-action $"coder record ($author) ($title)" "write"
  coder record $author $content --kind $kind --category $category --title $title --tags $tags --relates_to $relates_to --trigger $trigger --files_touched $files_touched --domain $domain --reusable=$reusable
}
def "main coder log" [--author (-a): string = "", --category (-c): string = "", --tag (-t): string = "", --kind (-k): string = "", --domain (-d): string = "", --limit (-l): int = 0] {
  log-action "coder log" "read"
  coder log --author $author --category $category --tag $tag --kind $kind --domain $domain --limit $limit
}
def "main coder export" [--author (-a): string = "", --category (-c): string = "", --format (-f): string = "json"] {
  log-action "coder export" "read"
  let f = (resolve-fmt $format [json jsonl csv])
  coder export --author $author --category $category --format $f
}
def "main coder triage" [author: string, --dry-run (-n), --interactive (-i)] {
  log-action $"coder triage ($author)" "write"
  coder triage $author --dry-run=$dry_run --interactive=$interactive
}
def "main coder ls" [author: string = "", --category (-c): string = ""] { log-action "coder ls" "read"; coder ls $author --category $category }
def "main coder search" [pattern: string, --author (-a): string = ""] { log-action $"coder search ($pattern)" "read"; coder search $pattern --author $author }
def "main coder publish" [author: string, category: string, --dry-run (-n), --all (-a)] {
  log-action $"coder publish ($author) ($category)" "write"
  coder publish $author $category --dry-run=$dry_run --all=$all
}
def "main coder graduate" [source_category: string, --target (-t): string = "reflection/knowledge", --dry-run (-n)] {
  log-action $"coder graduate ($source_category)" "write"
  coder graduate $source_category --target $target --dry-run=$dry_run
}

# ── Manifest ──────────────────────────────────────────────────────────────────

def "main manifest" [action?: string] { missing-target "manifest" $action }
def "main manifest help" [] { help-group "manifest" }
def "main manifest mode" [id: string, --dry-run (-n)] { log-action $"manifest mode ($id)" "read"; manifest mode $id --dry-run=$dry_run }
def "main manifest mode list" [--fmt (-f): string = "table"] {
  log-action "manifest mode list" "read"
  let f = (resolve-fmt $fmt [table json yaml toml])
  manifest mode list --fmt $f
}
def "main manifest publish" [id: string, --dry-run (-n), --yes (-y)] {
  log-action $"manifest publish ($id)" "write"
  manifest publish $id --dry-run=$dry_run --yes=$yes
}
def "main manifest publish list" [--fmt (-f): string = "table"] {
  log-action "manifest publish list" "read"
  let f = (resolve-fmt $fmt [table json yaml toml])
  manifest publish list --fmt $f
}
def "main manifest layers" [--mode (-m): string = ""] { log-action "manifest layers" "read"; manifest layers --mode $mode }
def "main manifest consumers" [--fmt (-f): string = "table"] {
  log-action "manifest consumers" "read"
  let f = (resolve-fmt $fmt [table json yaml toml])
  manifest consumers --fmt $f
}

# ── Describe ──────────────────────────────────────────────────────────────────

def "main describe" [action?: string] { missing-target "describe" $action }
def "main describe help" [] { help-group "describe" }
def "main describe project" [--fmt (-f): string = "", --actor: string = ""] {
  log-action "describe project" "read"
  let f = (resolve-fmt $fmt [text table json yaml toml]); describe project --fmt $f --actor $actor
}
def "main describe capabilities" [--fmt (-f): string = "", --actor: string = ""] {
  log-action "describe capabilities" "read"
  let f = (resolve-fmt $fmt [text table json yaml toml]); describe capabilities --fmt $f --actor $actor
}
def "main describe constraints" [--fmt (-f): string = "", --actor: string = ""] {
  log-action "describe constraints" "read"
  let f = (resolve-fmt $fmt [text table json yaml toml]); describe constraints --fmt $f --actor $actor
}
def "main describe tools" [--fmt (-f): string = "", --actor: string = ""] {
  log-action "describe tools" "read"
  let f = (resolve-fmt $fmt [text table json yaml toml]); describe tools --fmt $f --actor $actor
}
def "main describe impact" [node_id: string, --depth: int = 2, --fmt (-f): string = ""] {
  log-action $"describe impact ($node_id)" "read"
  let f = (resolve-fmt $fmt [text table json yaml toml]); describe impact $node_id --depth $depth --fmt $f
}
def "main describe why" [id: string, --fmt (-f): string = ""] {
  log-action $"describe why ($id)" "read"
  let f = (resolve-fmt $fmt [text table json yaml toml]); describe why $id --fmt $f
}
def "main describe find" [term: string, --level: string = "", --fmt (-f): string = ""] {
  log-action $"describe find ($term)" "read"
  describe find $term --level $level --fmt $fmt
}

def "main describe features" [id?: string, --fmt (-f): string = "", --actor: string = ""] {
  log-action $"describe features ($id | default '')" "read"
  let f = (resolve-fmt $fmt [text table json yaml toml])
  if ($id | is-empty) or ($id == "") { describe features --fmt $f --actor $actor } else { describe features $id --fmt $f --actor $actor }
}

def "main describe connections" [--fmt (-f): string = "", --actor: string = ""] {
  log-action "describe connections" "read"
  let f = (resolve-fmt $fmt [text json])
  describe connections --fmt $f --actor $actor
}

# ── Diagram ───────────────────────────────────────────────────────────────────

def "main diagram" [] {
  log-action "diagram" "read"
  let root = (project-root)
  let project_diagram = $"($root)/assets/main-diagram.md"
  let onref_diagram = $"($env.ONTOREF_ROOT)/assets/main-diagram.md"
  let diagram_file = if ($project_diagram | path exists) {
    $project_diagram
  } else if ($onref_diagram | path exists) {
    $onref_diagram
  } else {
    print "  Diagram not found"
    return
  }
  let content = (open $diagram_file --raw)
  let stripped = ($content | lines | where { |l| not ($l | str starts-with "```") } | str join "\n")
  print $stripped
}

# ── About ─────────────────────────────────────────────────────────────────────

def "main about" [] {
  log-action "about" "read"
  let root = (project-root)
  let name = ($root | path basename)
  let ascii_file = $"($root)/assets/($name)_ascii.txt"
  if ($ascii_file | path exists) {
    let ascii = (open $ascii_file --raw)
    print ""
    print $ascii
  }
  let project_about = $"($root)/assets/about.md"
  let onref_about = $"($env.ONTOREF_ROOT)/assets/about.md"
  let about_file = if ($project_about | path exists) {
    $project_about
  } else if ($onref_about | path exists) {
    $onref_about
  } else {
    print "  About not found"
    return
  }
  let content = (open $about_file --raw)
  print $content
}

# ── Overview / Health / Status ────────────────────────────────────────────────

def "main overview" [--fmt (-f): string = ""] {
  log-action "overview" "read"
  let f = (resolve-fmt $fmt [text table json yaml toml])
  run-overview $f
}

def "main health" [--fmt (-f): string = "", --full] {
  log-action "health" "read"
  let f = (resolve-fmt $fmt [text table json yaml toml])
  run-health $f $full
}

def "main status" [--fmt (-f): string = ""] {
  log-action "status" "read"
  let f = (resolve-fmt $fmt [text table json yaml toml])
  run-status $f
}

# ── Log ──────────────────────────────────────────────────────────────────────

def "main log" [
  action?: string,
  --follow (-f),
  --latest (-l),
  --since: string = "",
  --until: string = "",
  --tail: int = -1,
  --timestamps (-t),
  --level: string = "",
  --actor: string = "",
  --query (-q): list<string> = [],
  --fmt: string = "text",
] {
  let act = ($action | default "")
  if $act == "h" or $act == "help" {
    help-group "log"
    return
  }
  if $act == "config" {
    log-show-config
    return
  }
  if $follow {
    log-follow --timestamps=$timestamps --query $query
    return
  }
  log-query --tail_n $tail --since $since --until $until --latest=$latest --timestamps=$timestamps --level $level --actor $actor --query $query --fmt $fmt
}

def "main log record" [
  action: string,
  --level (-l): string = "write",
  --author (-a): string = "",
  --actor: string = "",
] {
  log-record $action --level $level --author $author --actor $actor
}

# ── Aliases ───────────────────────────────────────────────────────────────────
# All aliases delegate to canonical commands → single log-action call site.
# ad=adr, d=describe, ck=check, con=constraint, rg=register, f=find, ru=run,
# bkl=backlog, cfg=config, cod=coder, mf=manifest, dg=diagram, md=mode, fm=form, st=status, h=help

def "main ad" [action?: string] { main adr $action }
def "main ad help" [] { help-group "adr" }
def "main ad list" [--fmt (-f): string = ""] { main adr list --fmt $fmt }
def "main ad l" [--fmt (-f): string = ""] { main adr list --fmt $fmt }
def "main ad validate" [] { main adr validate }
def "main ad accept" [id: string] { main adr accept $id }
def "main ad a" [id: string] { main adr accept $id }
def "main ad show" [id?: string, --interactive (-i), --fmt (-f): string = ""] { main adr show $id --interactive=$interactive --fmt $fmt }
def "main ad s" [id?: string, --interactive (-i), --fmt (-f): string = ""] { main adr show $id --interactive=$interactive --fmt $fmt }

def "main ck" [--context: string = "", --form: string = "", --severity: string = "", --json] { main check --context $context --form $form --severity $severity --json=$json }

def "main con" [--fmt (-f): string = ""] { main constraint --fmt $fmt }
def "main rg" [--backend: string = "cli"] { main register --backend $backend }

def "main d" [action?: string] { main describe $action }
def "main d help" [] { help-group "describe" }
def "main d project" [--fmt (-f): string = "", --actor: string = ""] { main describe project --fmt $fmt --actor $actor }
def "main d p" [--fmt (-f): string = "", --actor: string = ""] { main describe project --fmt $fmt --actor $actor }
def "main d capabilities" [--fmt (-f): string = "", --actor: string = ""] { main describe capabilities --fmt $fmt --actor $actor }
def "main d cap" [--fmt (-f): string = "", --actor: string = ""] { main describe capabilities --fmt $fmt --actor $actor }
def "main d constraints" [--fmt (-f): string = "", --actor: string = ""] { main describe constraints --fmt $fmt --actor $actor }
def "main d con" [--fmt (-f): string = "", --actor: string = ""] { main describe constraints --fmt $fmt --actor $actor }
def "main d tools" [--fmt (-f): string = "", --actor: string = ""] { main describe tools --fmt $fmt --actor $actor }
def "main d t" [--fmt (-f): string = "", --actor: string = ""] { main describe tools --fmt $fmt --actor $actor }
def "main d tls" [--fmt (-f): string = "", --actor: string = ""] { main describe tools --fmt $fmt --actor $actor }
def "main d find" [term: string, --level: string = "", --fmt (-f): string = ""] { main describe find $term --level $level --fmt $fmt }
def "main d fi" [term: string, --level: string = "", --fmt (-f): string = ""] { main describe find $term --level $level --fmt $fmt }
def "main d features" [id?: string, --fmt (-f): string = "", --actor: string = ""] { main describe features $id --fmt $fmt --actor $actor }
def "main d fea" [id?: string, --fmt (-f): string = "", --actor: string = ""] { main describe features $id --fmt $fmt --actor $actor }
def "main d f" [id?: string, --fmt (-f): string = "", --actor: string = ""] { main describe features $id --fmt $fmt --actor $actor }
def "main d impact" [node_id: string, --depth: int = 2, --fmt (-f): string = ""] { main describe impact $node_id --depth $depth --fmt $fmt }
def "main d i" [node_id: string, --depth: int = 2, --fmt (-f): string = ""] { main describe impact $node_id --depth $depth --fmt $fmt }
def "main d imp" [node_id: string, --depth: int = 2, --fmt (-f): string = ""] { main describe impact $node_id --depth $depth --fmt $fmt }
def "main d why" [id: string, --fmt (-f): string = ""] { main describe why $id --fmt $fmt }
def "main d w" [id: string, --fmt (-f): string = ""] { main describe why $id --fmt $fmt }
def "main d connections" [--fmt (-f): string = "", --actor: string = ""] { main describe connections --fmt $fmt --actor $actor }
def "main d conn" [--fmt (-f): string = "", --actor: string = ""] { main describe connections --fmt $fmt --actor $actor }

def "main bkl" [action?: string] { main backlog $action }
def "main bkl help" [] { help-group "backlog" }
def "main bkl roadmap" [] { main backlog roadmap }
def "main bkl r" [] { main backlog roadmap }
def "main bkl list" [--status: string = "", --kind: string = "", --fmt (-f): string = ""] { main backlog list --status $status --kind $kind --fmt $fmt }
def "main bkl l" [--status: string = "", --kind: string = "", --fmt (-f): string = ""] { main backlog list --status $status --kind $kind --fmt $fmt }
def "main bkl show" [id: string] { main backlog show $id }
def "main bkl add" [title: string, --kind: string = "Todo", --priority: string = "Medium", --detail: string = "", --dim: string = "", --adr: string = "", --mode: string = ""] {
  main backlog add $title --kind $kind --priority $priority --detail $detail --dim $dim --adr $adr --mode $mode
}
def "main bkl done" [id: string] { main backlog done $id }
def "main bkl cancel" [id: string] { main backlog cancel $id }
def "main bkl promote" [id: string] { main backlog promote $id }
def "main bkl p" [id: string] { main backlog promote $id }

def "main cfg" [action?: string] { main config $action }
def "main cfg help" [] { help-group "config" }
def "main cfg show" [profile: string, --fmt (-f): string = ""] { main config show $profile --fmt $fmt }
def "main cfg history" [profile: string, --fmt (-f): string = ""] { main config history $profile --fmt $fmt }
def "main cfg diff" [profile: string, from_id: string, to_id: string] { main config diff $profile $from_id $to_id }
def "main cfg verify" [profile: string] { main config verify $profile }
def "main cfg audit" [] { main config audit }
def "main cfg apply" [profile: string, --adr: string = "", --pr: string = "", --bug: string = "", --note: string = ""] { main config apply $profile --adr $adr --pr $pr --bug $bug --note $note }
def "main cfg rollback" [profile: string, to_id: string, --adr: string = "", --note: string = ""] { main config rollback $profile $to_id --adr $adr --note $note }

def "main cod" [action?: string] { main coder $action }
def "main cod help" [] { help-group "coder" }
def "main cod authors" [] { main coder authors }
def "main cod init" [author: string, --actor: string = "Human", --model: string = ""] { main coder init $author --actor $actor --model $model }
def "main cod record" [
  author: string, content: string,
  --kind (-k): string = "info", --category (-c): string = "", --title (-t): string,
  --tags: list<string> = [], --relates_to: list<string> = [],
  --trigger: string = "", --files_touched: list<string> = [],
  --domain (-d): string = "", --reusable (-r),
] { main coder record $author $content --kind $kind --category $category --title $title --tags $tags --relates_to $relates_to --trigger $trigger --files_touched $files_touched --domain $domain --reusable=$reusable }
def "main cod log" [--author (-a): string = "", --category (-c): string = "", --tag (-t): string = "", --kind (-k): string = "", --domain (-d): string = "", --limit (-l): int = 0] {
  main coder log --author $author --category $category --tag $tag --kind $kind --domain $domain --limit $limit
}
def "main cod export" [--author (-a): string = "", --category (-c): string = "", --format (-f): string = "json"] { main coder export --author $author --category $category --format $format }
def "main cod triage" [author: string, --dry-run (-n), --interactive (-i)] { main coder triage $author --dry-run=$dry_run --interactive=$interactive }
def "main cod ls" [author: string = "", --category (-c): string = ""] { main coder ls $author --category $category }
def "main cod search" [pattern: string, --author (-a): string = ""] { main coder search $pattern --author $author }
def "main cod publish" [author: string, category: string, --dry-run (-n), --all (-a)] { main coder publish $author $category --dry-run=$dry_run --all=$all }
def "main cod graduate" [source_category: string, --target (-t): string = "reflection/knowledge", --dry-run (-n)] { main coder graduate $source_category --target $target --dry-run=$dry_run }

def "main mf" [action?: string] { main manifest $action }
def "main mf help" [] { help-group "manifest" }
def "main mf mode" [id: string, --dry-run (-n)] { main manifest mode $id --dry-run=$dry_run }
def "main mf mode list" [--fmt (-f): string = "table"] { main manifest mode list --fmt $fmt }
def "main mf publish" [id: string, --dry-run (-n), --yes (-y)] { main manifest publish $id --dry-run=$dry_run --yes=$yes }
def "main mf publish list" [--fmt (-f): string = "table"] { main manifest publish list --fmt $fmt }
def "main mf layers" [--mode (-m): string = ""] { main manifest layers --mode $mode }
def "main mf consumers" [--fmt (-f): string = "table"] { main manifest consumers --fmt $fmt }

def "main md" [action?: string] { main mode $action }
def "main md help" [] { main mode help }
def "main md list" [--fmt (-f): string = ""] { main mode list --fmt $fmt }
def "main md l" [--fmt (-f): string = ""] { main mode list --fmt $fmt }
def "main md show" [id: string, --fmt (-f): string = ""] { main mode show $id --fmt $fmt }
def "main md s" [id: string, --fmt (-f): string = ""] { main mode show $id --fmt $fmt }
def "main md run" [id: string, --dry-run (-n), --yes (-y)] { main mode run $id --dry-run=$dry_run --yes=$yes }
def "main md select" [] { main mode select }

def "main fm" [action?: string] { main form $action }
def "main fm help" [] { main form help }
def "main fm list" [] { main form list }
def "main fm l" [] { main form list }
def "main fm run" [name: string, --backend: string = "cli"] { main form run $name --backend $backend }

def "main st" [--fmt (-f): string = ""] { main status --fmt $fmt }

def "main run" [id?: string, --dry-run (-n), --yes (-y)] {
  let act = ($id | default "")
  if $act == "" or $act == "?" or $act == "select" {
    let mode_id = (pick-mode)
    if ($mode_id | is-empty) { return }
    main mode run $mode_id --dry-run=$dry_run --yes=$yes
    return
  }
  if $act == "l" or $act == "list" { main mode list; return }
  if $act == "h" or $act == "help" { help-group "mode"; return }
  main mode run $act --dry-run=$dry_run --yes=$yes
}
def "main ru" [id?: string, --dry-run (-n), --yes (-y)] { main run $id --dry-run=$dry_run --yes=$yes }

def "main find" [term: string, --level: string = "", --fmt (-f): string = ""] { main describe find $term --level $level --fmt $fmt }
def "main f" [term: string, --level: string = "", --fmt (-f): string = ""] { main describe find $term --level $level --fmt $fmt }

def "main dg" [] { main diagram }
def "main h" [group?: string] { main help $group }

# ── NATS Events ───────────────────────────────────────────────────────────────

def "main nats" [action?: string]: nothing -> nothing {
  match ($action | default "") {
    "" => { nats-status },
    "status" => { nats-status },
    "listen" => { nats-listen },
    "emit" => { print "Usage: onref nats emit <event> [--project X]"; },
    _ => { print $"Unknown action: ($action). Use: status, listen, emit" }
  }
}

def "main nv" [action?: string]: nothing -> nothing { main nats $action }

# ── Services ──────────────────────────────────────────────────────────────────

def "main services" [action?: string, id?: string] {
  services $action $id
}

def "main sv" [action?: string, id?: string] { main services $action $id }

# ── Init ──────────────────────────────────────────────────────────────────────

def "main init" [] {
  let root  = ($env.ONTOREF_PROJECT_ROOT? | default $env.ONTOREF_ROOT)
  let actor = ($env.ONTOREF_ACTOR? | default "developer")
  let cfg_path = $"($root)/.ontoref/config.ncl"

  let init_entry = if ($cfg_path | path exists) {
    let cfg = (daemon-export-safe $cfg_path)
    if $cfg != null {
      $cfg | get actor_init? | default [] | where { |e| $e.actor == $actor } | first | default null
    } else { null }
  } else { null }

  if $init_entry != null and ($init_entry.auto_run? | default false) and ($init_entry.mode? | default "" | is-not-empty) {
    print $"  init: running '($init_entry.mode)' for actor ($actor)"
    run-mode ($init_entry.mode)
  } else {
    print $"  Actor: ($actor) — no init mode configured"
    print $"  Run 'onref help mode' to see available modes"
  }
}
