#!/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
#   scale     Dynamic agent scaling
#   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 scale shepherd 3       Scale shepherd pool to 3
#   ./.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
        # Use existing loom-status.sh if available
        if [[ -f "$REPO_ROOT/.loom/scripts/loom-status.sh" ]]; then
            exec "$REPO_ROOT/.loom/scripts/loom-status.sh" "$@"
        elif [[ -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
        loom_venv="$REPO_ROOT/loom-tools/.venv/bin/loom-daemon-diagnostic"
        if [[ -n "$REPO_ROOT" && -x "$loom_venv" ]]; then
            exec "$loom_venv" "$@"
        elif command -v loom-daemon-diagnostic &>/dev/null; then
            exec loom-daemon-diagnostic "$@"
        else
            echo -e "${RED}Error: health command not installed (install loom-tools)${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
        ;;
    scale)
        shift
        if [[ -f "$CLI_DIR/loom-scale.sh" ]]; then
            exec "$CLI_DIR/loom-scale.sh" "$@"
        else
            echo -e "${RED}Error: loom-scale.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
    scale     Dynamic agent scaling
    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 "/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 scale shepherd 3       Scale shepherd pool to 3
    ./.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
