#!/usr/bin/env bash
#clear
#export PS4='\e[90m+${LINENO} in ${#BASH_SOURCE[@]}>${FUNCNAME[0]}:${BASH_SOURCE[@]##*/} \e[0m'
#set -x

#echo "starting: $0 <LOG_LEVEL=$1>"

### new.method

# ============================================================================
# claudeFlow - Claude Flow wrapper for oosh
# Makes Claude Flow CLI commands easy to use with intuitive method names
# ============================================================================

# ─────────────────────────────────────────────────────────────────────────────
# SYSTEM COMMANDS
# ─────────────────────────────────────────────────────────────────────────────

claudeFlow.init() # <?path> # initialize claude flow in a directory
{
  if [ -n "$1" ]; then
    claude-flow init "$1"
  else
    claude-flow init
  fi
}

claudeFlow.start() # <?options> # start the orchestration system
{
  claude-flow start "$@"
}

claudeFlow.stop() # # stop the orchestration system
{
  claude-flow start stop
}

claudeFlow.restart() # # restart the orchestration system
{
  claude-flow start restart
}

claudeFlow.quick() # # quick start with default settings
{
  claude-flow start quick
}

claudeFlow.daemon() # <?options> # start as background daemon
{
  claude-flow start --daemon "$@"
}

claudeFlow.status() # # show system status
{
  claude-flow status
  echo ""
  echo "Claude Flow wrapper for oosh"
  echo "Type 'claudeFlow' for interactive mode"
  echo "Type 'claudeFlow help' for all options"
}

claudeFlow.doctor() # # run diagnostics and health checks
{
  claude-flow doctor
}

claudeFlow.version() # # show claude-flow version
{
  claude-flow --version
}

claudeFlow.v() # # shorthand for version
{
  claudeFlow.version
}

claudeFlow.help() # # show claude-flow help
{
  claude-flow --help
}

claudeFlow.install() # # install claude-flow via npm
{
  # Check if npm is available
  if ! command -v npm &> /dev/null; then
    error.log "npm is required but not installed."
    error.log "Please install Node.js and npm first:"
    echo "  curl -fsSL https://deb.nodesource.com/setup_lts.x | sudo -E bash -"
    echo "  sudo apt-get install -y nodejs"
    return 1
  fi

  # Check if already installed
  if command -v claude-flow &> /dev/null; then
    info.log "Claude Flow is already installed: $(which claude-flow)"
    claude-flow --version
    echo ""
    read -p "Reinstall/update anyway? [y/N] " -n 1 -r
    echo
    if [[ ! $REPLY =~ ^[Yy]$ ]]; then
      info.log "Installation cancelled"
      return 0
    fi
  fi

  info.log "Installing Claude Flow via npm..."

  # Install globally via npm
  npm install -g claude-flow

  if [ $? -ne 0 ]; then
    error.log "Installation failed"
    error.log "Try running with sudo: sudo npm install -g claude-flow"
    return 1
  fi

  # Verify installation
  if command -v claude-flow &> /dev/null; then
    success.log "Claude Flow installed successfully!"
    claude-flow --version
    echo ""
    info.log "Run 'claudeFlow init' to initialize in a directory"
    info.log "Run 'claudeFlow doctor' to verify setup"
  else
    error.log "Installation completed but 'claude-flow' command not found"
    error.log "Check that npm global bin is in your PATH"
    return 1
  fi
}

claudeFlow.uninstall() # # uninstall claude-flow
{
  if ! command -v claude-flow &> /dev/null; then
    warn.log "Claude Flow does not appear to be installed"
    return 0
  fi

  local install_path=$(which claude-flow)
  info.log "Claude Flow is installed at: $install_path"
  claude-flow --version
  echo ""
  read -p "Are you sure you want to uninstall Claude Flow? [y/N] " -n 1 -r
  echo

  if [[ ! $REPLY =~ ^[Yy]$ ]]; then
    info.log "Uninstall cancelled"
    return 0
  fi

  info.log "Uninstalling Claude Flow via npm..."

  npm uninstall -g claude-flow

  if [ $? -ne 0 ]; then
    error.log "Uninstall failed"
    error.log "Try running with sudo: sudo npm uninstall -g claude-flow"
    return 1
  fi

  if ! command -v claude-flow &> /dev/null; then
    success.log "Claude Flow uninstalled successfully"
  else
    warn.log "claude-flow command still found - may need manual removal"
  fi
}

claudeFlow.update() # # update claude-flow to latest version
{
  if ! command -v claude-flow &> /dev/null; then
    warn.log "Claude Flow is not installed. Run 'claudeFlow install' first."
    return 1
  fi

  info.log "Current version:"
  claude-flow --version
  echo ""
  info.log "Updating Claude Flow via npm..."

  npm update -g claude-flow

  if [ $? -ne 0 ]; then
    error.log "Update failed"
    error.log "Try running with sudo: sudo npm update -g claude-flow"
    return 1
  fi

  success.log "Claude Flow updated!"
  claude-flow --version
}

# ─────────────────────────────────────────────────────────────────────────────
# AGENT COMMANDS
# ─────────────────────────────────────────────────────────────────────────────

claudeFlow.agent() # <subcommand> # agent management commands
{
  claude-flow agent "$@"
}

claudeFlow.agent.spawn() # <options> # spawn a new agent
{
  claude-flow agent spawn "$@"
}
claudeFlow.agent.spawn.completion.type() {
  echo "coder"
  echo "researcher"
  echo "reviewer"
  echo "planner"
}

claudeFlow.agent.list() # # list all active agents
{
  claude-flow agent list "$@"
}

claudeFlow.agent.ls() # # shorthand for agent list
{
  claudeFlow.agent.list "$@"
}

claudeFlow.agent.status() # <agent-id> # show agent status
{
  claude-flow agent status "$@"
}

claudeFlow.agent.stop() # <agent-id> # stop a running agent
{
  claude-flow agent stop "$@"
}

claudeFlow.agent.kill() # <agent-id> # alias for agent stop
{
  claudeFlow.agent.stop "$@"
}

claudeFlow.agent.metrics() # <?agent-id> # show agent performance metrics
{
  claude-flow agent metrics "$@"
}

claudeFlow.agent.pool() # <options> # manage agent pool for scaling
{
  claude-flow agent pool "$@"
}

claudeFlow.agent.health() # <?agent-id> # show agent health
{
  claude-flow agent health "$@"
}

claudeFlow.agent.logs() # <?agent-id> # show agent activity logs
{
  claude-flow agent logs "$@"
}

# ─────────────────────────────────────────────────────────────────────────────
# TASK COMMANDS
# ─────────────────────────────────────────────────────────────────────────────

claudeFlow.task() # <subcommand> # task management commands
{
  claude-flow task "$@"
}

claudeFlow.task.create() # <options> # create a new task
{
  claude-flow task create "$@"
}

claudeFlow.task.new() # <options> # alias for task create
{
  claudeFlow.task.create "$@"
}

claudeFlow.task.list() # <?options> # list tasks
{
  claude-flow task list "$@"
}

claudeFlow.task.ls() # <?options> # shorthand for task list
{
  claudeFlow.task.list "$@"
}

claudeFlow.task.all() # # list all tasks including completed
{
  claude-flow task list --all
}

claudeFlow.task.status() # <task-id> # get task status and details
{
  claude-flow task status "$@"
}

claudeFlow.task.info() # <task-id> # alias for task status
{
  claudeFlow.task.status "$@"
}

claudeFlow.task.cancel() # <task-id> # cancel a running task
{
  claude-flow task cancel "$@"
}

claudeFlow.task.assign() # <task-id> <options> # assign task to agent(s)
{
  claude-flow task assign "$@"
}

claudeFlow.task.retry() # <task-id> # retry a failed task
{
  claude-flow task retry "$@"
}

# ─────────────────────────────────────────────────────────────────────────────
# SESSION COMMANDS
# ─────────────────────────────────────────────────────────────────────────────

claudeFlow.session() # <subcommand> # session management commands
{
  claude-flow session "$@"
}

claudeFlow.session.list() # # list all sessions
{
  claude-flow session list "$@"
}

claudeFlow.session.ls() # # shorthand for session list
{
  claudeFlow.session.list "$@"
}

claudeFlow.session.save() # <?name> # save current session state
{
  claude-flow session save "$@"
}

claudeFlow.session.restore() # <session-id> # restore a saved session
{
  claude-flow session restore "$@"
}

claudeFlow.session.load() # <session-id> # alias for session restore
{
  claudeFlow.session.restore "$@"
}

claudeFlow.session.delete() # <session-id> # delete a saved session
{
  claude-flow session delete "$@"
}

claudeFlow.session.rm() # <session-id> # shorthand for session delete
{
  claudeFlow.session.delete "$@"
}

claudeFlow.session.export() # <options> # export session to file
{
  claude-flow session export "$@"
}

claudeFlow.session.import() # <file> # import session from file
{
  claude-flow session import "$@"
}

claudeFlow.session.current() # # show current active session
{
  claude-flow session current
}

# ─────────────────────────────────────────────────────────────────────────────
# SWARM COMMANDS
# ─────────────────────────────────────────────────────────────────────────────

claudeFlow.swarm() # <subcommand> # swarm coordination commands
{
  claude-flow swarm "$@"
}

claudeFlow.swarm.init() # <?options> # initialize a new swarm
{
  claude-flow swarm init "$@"
}

claudeFlow.swarm.v3() # <?options> # initialize V3 swarm with hierarchical mesh
{
  claude-flow swarm init --v3-mode "$@"
}

claudeFlow.swarm.start() # <options> # start swarm execution
{
  claude-flow swarm start "$@"
}

claudeFlow.swarm.status() # # show swarm status
{
  claude-flow swarm status "$@"
}

claudeFlow.swarm.stop() # # stop swarm execution
{
  claude-flow swarm stop "$@"
}

claudeFlow.swarm.scale() # <count> # scale swarm agent count
{
  claude-flow swarm scale "$@"
}

claudeFlow.swarm.coordinate() # <?options> # execute V3 15-agent hierarchical mesh coordination
{
  claude-flow swarm coordinate "$@"
}

# ─────────────────────────────────────────────────────────────────────────────
# MEMORY COMMANDS
# ─────────────────────────────────────────────────────────────────────────────

claudeFlow.memory() # <subcommand> # memory management commands
{
  claude-flow memory "$@"
}

claudeFlow.memory.init() # # initialize memory database
{
  claude-flow memory init "$@"
}

claudeFlow.memory.store() # <options> # store data in memory
{
  claude-flow memory store "$@"
}

claudeFlow.memory.get() # <key> # retrieve data from memory
{
  claude-flow memory retrieve "$@"
}

claudeFlow.memory.search() # <query> # search memory with semantic search
{
  claude-flow memory search "$@"
}

claudeFlow.memory.list() # # list memory entries
{
  claude-flow memory list "$@"
}

claudeFlow.memory.ls() # # shorthand for memory list
{
  claudeFlow.memory.list "$@"
}

claudeFlow.memory.delete() # <key> # delete memory entry
{
  claude-flow memory delete "$@"
}

claudeFlow.memory.rm() # <key> # shorthand for memory delete
{
  claudeFlow.memory.delete "$@"
}

claudeFlow.memory.stats() # # show memory statistics
{
  claude-flow memory stats
}

claudeFlow.memory.cleanup() # # clean up stale and expired entries
{
  claude-flow memory cleanup
}

claudeFlow.memory.compress() # # compress and optimize storage
{
  claude-flow memory compress
}

claudeFlow.memory.export() # <file> # export memory to file
{
  claude-flow memory export "$@"
}

claudeFlow.memory.import() # <file> # import memory from file
{
  claude-flow memory import "$@"
}

# ─────────────────────────────────────────────────────────────────────────────
# MCP COMMANDS
# ─────────────────────────────────────────────────────────────────────────────

claudeFlow.mcp() # <subcommand> # MCP server management
{
  claude-flow mcp "$@"
}

claudeFlow.mcp.start() # <?options> # start MCP server
{
  claude-flow mcp start "$@"
}

claudeFlow.mcp.stop() # # stop MCP server
{
  claude-flow mcp stop
}

claudeFlow.mcp.status() # # show MCP server status
{
  claude-flow mcp status
}

claudeFlow.mcp.health() # # check MCP server health
{
  claude-flow mcp health
}

claudeFlow.mcp.restart() # # restart MCP server
{
  claude-flow mcp restart
}

claudeFlow.mcp.tools() # # list available MCP tools
{
  claude-flow mcp tools "$@"
}

claudeFlow.mcp.toggle() # <tool> # enable or disable MCP tools
{
  claude-flow mcp toggle "$@"
}

claudeFlow.mcp.exec() # <tool> <options> # execute an MCP tool
{
  claude-flow mcp exec "$@"
}

claudeFlow.mcp.logs() # # show MCP server logs
{
  claude-flow mcp logs "$@"
}

# ─────────────────────────────────────────────────────────────────────────────
# HIVE-MIND COMMANDS
# ─────────────────────────────────────────────────────────────────────────────

claudeFlow.hive() # <subcommand> # hive-mind coordination commands
{
  claude-flow hive-mind "$@"
}

claudeFlow.hive.init() # <?options> # initialize a hive mind
{
  claude-flow hive-mind init "$@"
}

claudeFlow.hive.spawn() # <options> # spawn worker agents into the hive
{
  claude-flow hive-mind spawn "$@"
}

claudeFlow.hive.status() # # show hive mind status
{
  claude-flow hive-mind status "$@"
}

claudeFlow.hive.task() # <options> # submit tasks to the hive
{
  claude-flow hive-mind task "$@"
}

claudeFlow.hive.join() # <agent-id> # join an agent to the hive mind
{
  claude-flow hive-mind join "$@"
}

claudeFlow.hive.leave() # <agent-id> # remove an agent from the hive mind
{
  claude-flow hive-mind leave "$@"
}

claudeFlow.hive.consensus() # <options> # manage consensus proposals and voting
{
  claude-flow hive-mind consensus "$@"
}

claudeFlow.hive.broadcast() # <message> # broadcast message to all workers
{
  claude-flow hive-mind broadcast "$@"
}

claudeFlow.hive.memory() # # access hive shared memory
{
  claude-flow hive-mind memory "$@"
}

claudeFlow.hive.optimize() # # optimize hive memory and patterns
{
  claude-flow hive-mind optimize-memory "$@"
}

claudeFlow.hive.shutdown() # # shutdown the hive mind
{
  claude-flow hive-mind shutdown "$@"
}

# ─────────────────────────────────────────────────────────────────────────────
# HOOKS COMMANDS
# ─────────────────────────────────────────────────────────────────────────────

claudeFlow.hooks() # <subcommand> # self-learning hooks system
{
  claude-flow hooks "$@"
}

# ─────────────────────────────────────────────────────────────────────────────
# EMBEDDINGS COMMANDS
# ─────────────────────────────────────────────────────────────────────────────

claudeFlow.embeddings() # <subcommand> # vector embeddings and semantic search
{
  claude-flow embeddings "$@"
}

# ─────────────────────────────────────────────────────────────────────────────
# NEURAL COMMANDS
# ─────────────────────────────────────────────────────────────────────────────

claudeFlow.neural() # <subcommand> # neural pattern training and MoE
{
  claude-flow neural "$@"
}

# ─────────────────────────────────────────────────────────────────────────────
# PERFORMANCE COMMANDS
# ─────────────────────────────────────────────────────────────────────────────

claudeFlow.performance() # <subcommand> # profiling and benchmarking
{
  claude-flow performance "$@"
}

claudeFlow.perf() # <subcommand> # shorthand for performance
{
  claudeFlow.performance "$@"
}

# ─────────────────────────────────────────────────────────────────────────────
# SECURITY COMMANDS
# ─────────────────────────────────────────────────────────────────────────────

claudeFlow.security() # <subcommand> # security scanning and threat modeling
{
  claude-flow security "$@"
}

# ─────────────────────────────────────────────────────────────────────────────
# OUTPUT OPTIONS
# ─────────────────────────────────────────────────────────────────────────────

claudeFlow.verbose() # <command> # run with verbose output
{
  claude-flow --verbose "$@"
}

claudeFlow.quiet() # <command> # run with suppressed output
{
  claude-flow --quiet "$@"
}

claudeFlow.json() # <command> # output as JSON
{
  claude-flow --format json "$@"
}

claudeFlow.table() # <command> # output as table
{
  claude-flow --format table "$@"
}

claudeFlow.interactive() # <command> # enable interactive mode
{
  claude-flow --interactive "$@"
}

claudeFlow.i() # <command> # shorthand for interactive
{
  claudeFlow.interactive "$@"
}

# ─────────────────────────────────────────────────────────────────────────────
# USAGE & HELP
# ─────────────────────────────────────────────────────────────────────────────

claudeFlow.usage()
{
  local this=${0##*/}
  echo "You started"
  echo "$0

  claudeFlow - Claude Flow wrapper for oosh
  Makes cryptic commands easy to remember!

  Usage:
  $this: command     Description
  ─────────────────────────────────────────────────────
  SYSTEM:
      init            initialize claude flow
      start           start orchestration system
      stop            stop orchestration system
      restart         restart the system
      quick           quick start with defaults
      daemon          start as background daemon
      status          show system status
      doctor          run diagnostics
      v               show version

  INSTALLATION:
      install         install claude-flow via npm
      uninstall       remove claude-flow installation
      update          update to latest version

  AGENTS:
      agent.spawn     spawn a new agent
      agent.list      list all active agents
      agent.status    show agent status
      agent.stop      stop a running agent
      agent.metrics   show performance metrics
      agent.logs      show agent logs

  TASKS:
      task.create     create a new task
      task.list       list tasks
      task.status     get task status
      task.cancel     cancel a running task
      task.assign     assign task to agent(s)
      task.retry      retry a failed task

  SESSIONS:
      session.list    list all sessions
      session.save    save current session
      session.restore restore a session
      session.delete  delete a session
      session.export  export to file
      session.import  import from file

  SWARM:
      swarm.init      initialize swarm
      swarm.v3        initialize V3 swarm
      swarm.start     start swarm
      swarm.status    show swarm status
      swarm.stop      stop swarm
      swarm.scale     scale agent count
      swarm.coordinate V3 mesh coordination

  MEMORY:
      memory.init     initialize memory DB
      memory.store    store data
      memory.get      retrieve data
      memory.search   semantic search
      memory.stats    show statistics
      memory.cleanup  clean up stale data

  MCP:
      mcp.start       start MCP server
      mcp.stop        stop MCP server
      mcp.status      show server status
      mcp.tools       list available tools
      mcp.exec        execute a tool

  HIVE-MIND:
      hive.init       initialize hive mind
      hive.spawn      spawn worker agents
      hive.task       submit tasks
      hive.consensus  manage voting
      hive.broadcast  broadcast message
      hive.shutdown   shutdown hive

  OUTPUT:
      verbose         verbose output
      quiet           suppressed output
      json            JSON format
      table           table format
      i               interactive mode
  ─────────────────────────────────────────────────────

  Examples:
    $this start                        # start system
    $this agent.spawn -t coder         # spawn coder agent
    $this task.create -d 'Add auth'    # create task
    $this swarm.v3                     # init V3 swarm
    $this memory.search 'patterns'     # semantic search
    $this hive.spawn -n 5              # spawn 5 workers
  "
}

claudeFlow.start()
{
  #echo "sourcing init"
  source this

  if [ -z "$1" ]; then
    # No arguments - show status
    claudeFlow.status
    return 0
  fi

  this.start "$@"
}

claudeFlow.start "$@"
