#!/usr/bin/env bash
# Loom CLI - tmux agent pool management
#
# Usage: ./.loom/bin/loom <command> [options]
#
# Commands:
#   start     Spawn agent pool from config
#   status    Display agent pool state
#   health    Diagnostic daemon health check
#   stop      Graceful shutdown
#   attach    Open live tmux session
#   send      Send command to agent session
#   logs      Tail agent output
#   help      Show help
#
# Examples:
#   ./.loom/bin/loom start                  Start all configured agents
#   ./.loom/bin/loom start --only shepherd  Start only shepherd agents
#   ./.loom/bin/loom status                 Show current state
#   ./.loom/bin/loom attach shepherd-1      Connect to terminal
#   ./.loom/bin/loom stop                   Graceful shutdown
#   ./.loom/bin/loom stop --force           Force kill all sessions
#   ./.loom/bin/loom logs terminal-1        Tail agent output
#
# For more details:
#   ./.loom/bin/loom help
#   ./.loom/bin/loom <command> --help

set -euo pipefail

# Determine script location (works even when symlinked)
if [[ -L "${BASH_SOURCE[0]}" ]]; then
    SCRIPT_DIR="$(cd "$(dirname "$(readlink "${BASH_SOURCE[0]}")")" && pwd)"
else
    SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
fi

# Find the repository root by looking for .loom directory
find_repo_root() {
    local dir="$PWD"
    while [[ "$dir" != "/" ]]; do
        if [[ -d "$dir/.loom" ]]; then
            echo "$dir"
            return 0
        fi
        # Check if this is a worktree by looking for .git file
        if [[ -f "$dir/.git" ]]; then
            local gitdir
            gitdir=$(sed 's/^gitdir: //' "$dir/.git")
            local main_repo
            main_repo=$(dirname "$(dirname "$(dirname "$gitdir")")")
            if [[ -d "$main_repo/.loom" ]]; then
                echo "$main_repo"
                return 0
            fi
        fi
        dir="$(dirname "$dir")"
    done
    echo ""
}

REPO_ROOT=$(find_repo_root)
if [[ -z "$REPO_ROOT" ]]; then
    echo "Error: Not in a Loom workspace (.loom directory not found)" >&2
    echo "Run 'loom help' or initialize Loom in this repository" >&2
    exit 1
fi

CLI_DIR="$REPO_ROOT/.loom/scripts/cli"

# ANSI colors (disabled if not a terminal)
if [[ -t 1 ]]; then
    RED='\033[0;31m'
    YELLOW='\033[1;33m'
    NC='\033[0m'
else
    RED=''
    YELLOW=''
    NC=''
fi

# Dispatch to subcommands
case "${1:-help}" in
    start)
        shift
        if [[ -f "$CLI_DIR/loom-start.sh" ]]; then
            exec "$CLI_DIR/loom-start.sh" "$@"
        else
            echo -e "${RED}Error: loom-start.sh not found${NC}" >&2
            exit 1
        fi
        ;;
    status)
        shift
        if [[ -f "$CLI_DIR/loom-status.sh" ]]; then
            exec "$CLI_DIR/loom-status.sh" "$@"
        else
            echo -e "${RED}Error: loom-status.sh not found${NC}" >&2
            exit 1
        fi
        ;;
    health)
        shift
        # The former Python daemon-diagnostic CLI was removed in epic #4081
        # phase 3 (#4274). Daemon/registry health is now reported natively by
        # `loom-daemon status` (Issue #3891). Resolve the binary via the
        # shared loom_locate_daemon_bin() (lib/locate-daemon-bin.sh, #4875) so
        # this command, loom-daemon-start.sh, loom-daemon-watchdog.sh,
        # loom-daemon-update.sh and loom-status.sh all agree on which binary
        # is "the" daemon CLI -- including the LOOM_DAEMON_BIN override (this
        # branch previously had none) and the machine-level ~/.local/bin
        # fallback (needed under a non-interactive `ssh host 'cmd'`, which
        # never sources the login profile that would otherwise put
        # ~/.local/bin on PATH).
        _LOOM_LOCATE_BIN_LIB="$REPO_ROOT/.loom/scripts/lib/locate-daemon-bin.sh"
        loom_daemon_bin=""
        if [[ -r "$_LOOM_LOCATE_BIN_LIB" ]]; then
            # shellcheck source=/dev/null
            source "$_LOOM_LOCATE_BIN_LIB"
            loom_daemon_bin="$(loom_locate_daemon_bin "$REPO_ROOT")"
        fi
        if [[ -n "$loom_daemon_bin" ]]; then
            exec "$loom_daemon_bin" status "$@"
        else
            echo -e "${RED}Error: health command requires the loom-daemon binary. Checked:${NC}" >&2
            if [[ -r "$_LOOM_LOCATE_BIN_LIB" ]]; then
                loom_daemon_bin_search_paths "$REPO_ROOT" | sed 's/^/  - /' >&2
            fi
            echo -e "${RED}Build it (cargo build --release -p loom-daemon), install it to one of the paths above, or set LOOM_DAEMON_BIN=/path/to/loom-daemon${NC}" >&2
            exit 1
        fi
        ;;
    stop)
        shift
        if [[ -f "$CLI_DIR/loom-stop.sh" ]]; then
            exec "$CLI_DIR/loom-stop.sh" "$@"
        else
            echo -e "${RED}Error: loom-stop.sh not found${NC}" >&2
            exit 1
        fi
        ;;
    attach)
        shift
        if [[ -f "$CLI_DIR/loom-attach.sh" ]]; then
            exec "$CLI_DIR/loom-attach.sh" "$@"
        else
            echo -e "${RED}Error: loom-attach.sh not found${NC}" >&2
            exit 1
        fi
        ;;
    logs)
        shift
        if [[ -f "$CLI_DIR/loom-logs.sh" ]]; then
            exec "$CLI_DIR/loom-logs.sh" "$@"
        else
            echo -e "${RED}Error: loom-logs.sh not found${NC}" >&2
            exit 1
        fi
        ;;
    send)
        shift
        if [[ -f "$CLI_DIR/loom-send.sh" ]]; then
            exec "$CLI_DIR/loom-send.sh" "$@"
        else
            echo -e "${RED}Error: loom-send.sh not found${NC}" >&2
            exit 1
        fi
        ;;
    help|--help|-h)
        shift || true
        if [[ -f "$CLI_DIR/loom-help.sh" ]]; then
            exec "$CLI_DIR/loom-help.sh" "$@"
        else
            # Inline help if loom-help.sh not yet installed
            cat <<'EOF'
Loom CLI - tmux agent pool management

USAGE:
    ./.loom/bin/loom <command> [options]

COMMANDS:
    start     Spawn agent pool from .loom/config.json
    status    Display agent pool state and work queues
    health    Diagnostic daemon health check
    stop      Graceful shutdown (or --force to kill immediately)
    attach    Open live tmux session for an agent
    send      Send command to agent session
    logs      Tail agent output
    help      Show this help message

EXAMPLES:
    ./.loom/bin/loom start                  Start all configured agents
    ./.loom/bin/loom start --only shepherd  Start only shepherd agents
    ./.loom/bin/loom status                 Show current state
    ./.loom/bin/loom status --json          Machine-readable status
    ./.loom/bin/loom attach shepherd-1      Connect to agent terminal
    ./.loom/bin/loom send shepherd-1 "/loom:shepherd 123"  Send command to agent
    ./.loom/bin/loom stop                   Graceful shutdown
    ./.loom/bin/loom stop --force           Force kill all sessions
    ./.loom/bin/loom stop shepherd-1        Stop single agent
    ./.loom/bin/loom logs terminal-1        Tail agent output
    ./.loom/bin/loom logs --all             Tail all agent logs

For command-specific help:
    ./.loom/bin/loom <command> --help
EOF
            exit 0
        fi
        ;;
    version|--version|-v)
        echo "Loom CLI v0.1.0"
        exit 0
        ;;
    *)
        echo -e "${RED}Error: Unknown command '$1'${NC}" >&2
        echo "Run './.loom/bin/loom help' for available commands" >&2
        exit 1
        ;;
esac
