#!/bin/bash
# Taskmaster Master Helper
# Unified interface for all Taskmaster helper scripts

set -e

# Color codes
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
RED='\033[0;31m'
CYAN='\033[0;36m'
MAGENTA='\033[0;35m'
NC='\033[0m'

# Navigate to project root
cd "$(dirname "$0")/.."
PROJECT_ROOT=$(pwd)

# Set Task Master project root
export TM_PROJECT_ROOT="$PROJECT_ROOT"

# Function to print header
print_header() {
    echo -e "${CYAN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
    echo -e "${CYAN}$1${NC}"
    echo -e "${CYAN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
}

# Function to check if task-master is available
check_taskmaster() {
    if ! command -v task-master &> /dev/null; then
        echo -e "${RED}❌ task-master command not found${NC}"
        echo "Please install task-master-ai: npm install -g task-master-ai"
        exit 1
    fi
}

# Function to show quick overview
show_quick_overview() {
    print_header "🚀 TRAX TASKMASTER OVERVIEW"
    
    echo -e "${CYAN}📊 Quick Stats:${NC}"
    local total=$(task-master list 2>/dev/null | grep -c "│ [0-9]\+ │" || echo "0")
    local done=$(task-master list 2>/dev/null | grep -c "✓ done" || echo "0")
    local pending=$(task-master list 2>/dev/null | grep -c "│ ○        │" || echo "0")
    local in_progress=$(task-master list 2>/dev/null | grep -c "🔄 in-progress" || echo "0")
    
    echo -e "${GREEN}✅ Done: $done${NC}"
    echo -e "${YELLOW}🚧 In Progress: $in_progress${NC}"
    echo -e "${BLUE}📋 Pending: $pending${NC}"
    echo -e "${MAGENTA}📊 Total: $total${NC}"
    
    if [ "$total" -gt 0 ]; then
        local completion=$((done * 100 / total))
        echo -e "${CYAN}📈 Completion: ${completion}%${NC}"
    fi
    
    echo ""
    echo -e "${CYAN}🎯 Next Task:${NC}"
    task-master next 2>/dev/null | head -10 || echo "No next task found"
}

# Function to show available commands
show_commands() {
    print_header "🛠️  AVAILABLE COMMANDS"
    
    echo -e "${CYAN}📋 Status & Overview:${NC}"
    echo "  tm_status.sh [command]     - Status checking and overview"
    echo "    stats                    - Quick statistics"
    echo "    next                     - Show next task"
    echo "    pending                  - Show pending tasks"
    echo "    progress                 - Show in-progress tasks"
    echo "    full                     - Comprehensive overview"
    
    echo ""
    echo -e "${CYAN}🔍 Search & Discovery:${NC}"
    echo "  tm_search.sh [type] [term] - Search tasks by various criteria"
    echo "    text <term>              - Search by text"
    echo "    status <status>          - Search by status"
    echo "    priority <level>         - Search by priority"
    echo "    pipeline <version>       - Search by pipeline version"
    echo "    type <type>              - Search by task type"
    echo "    deps <task-id>           - Show dependencies"
    echo "    subtasks <task-id>       - Show subtasks"
    
    echo ""
    echo -e "${CYAN}🚀 Workflow Operations:${NC}"
    echo "  tm_workflow.sh [command]   - Workflow management"
    echo "    start <id>               - Start working on a task"
    echo "    update <id> <msg>        - Update task progress"
    echo "    complete <id>            - Complete a task"
    echo "    pause <id> [reason]      - Pause a task"
    echo "    review <id>              - Mark for review"
    echo "    expand <id> [num]        - Expand into subtasks"
    echo "    daily                    - Daily workflow overview"
    echo "    weekly                   - Weekly review"
    
    echo ""
    echo -e "${CYAN}🔍 Analysis & Insights:${NC}"
    echo "  tm_analyze.sh [command]    - Analysis and insights"
    echo "    analyze                  - Run complexity analysis"
    echo "    report                   - Show complexity report"
    echo "    dependencies             - Analyze dependencies"
    echo "    distribution             - Analyze task distribution"
    echo "    pipeline                 - Analyze pipeline progress"
    echo "    bottlenecks              - Identify bottlenecks"
    echo "    insights                 - Generate insights"
    echo "    full                     - Comprehensive analysis"
    
    echo ""
    echo -e "${CYAN}⚡ Quick Commands:${NC}"
    echo "  tm_quick.sh [command]      - Quick operations"
    echo "    next, n                  - Get next task"
    echo "    list, l                  - List all tasks"
    echo "    show, s <id>             - Show task details"
    echo "    done, d <id>             - Mark as done"
    echo "    progress, p <id>         - Mark as in-progress"
    echo "    search <term>            - Search tasks"
    echo "    stats                    - Show statistics"
}

# Function to show shortcuts
show_shortcuts() {
    print_header "⚡ QUICK SHORTCUTS"
    
    echo -e "${CYAN}🎯 Common Operations:${NC}"
    echo "  ./scripts/tm_master.sh overview    - Quick project overview"
    echo "  ./scripts/tm_master.sh next        - Get next task"
    echo "  ./scripts/tm_master.sh start <id>  - Start working on task"
    echo "  ./scripts/tm_master.sh done <id>   - Complete task"
    echo "  ./scripts/tm_master.sh search <term> - Search for tasks"
    echo "  ./scripts/tm_master.sh analyze     - Run analysis"
    echo "  ./scripts/tm_master.sh daily       - Daily workflow"
    
    echo ""
    echo -e "${CYAN}🔧 Direct Script Access:${NC}"
    echo "  ./scripts/tm_status.sh [command]   - Status operations"
    echo "  ./scripts/tm_search.sh [type] [term] - Search operations"
    echo "  ./scripts/tm_workflow.sh [command] - Workflow operations"
    echo "  ./scripts/tm_analyze.sh [command]  - Analysis operations"
    echo "  ./scripts/tm_quick.sh [command]    - Quick operations"

}

# Function to show help
show_help() {
    echo -e "${CYAN}🚀 Taskmaster Master Helper${NC}"
    echo ""
    echo "Usage: $0 [command] [args]"
    echo ""
    echo "Master Commands:"
    echo "  overview              - Quick project overview"
    echo "  next                  - Get next available task"
    echo "  start <id>            - Start working on a task"
    echo "  done <id>             - Complete a task"
    echo "  search <term>         - Search for tasks"
    echo "  analyze               - Run analysis"
    echo "  daily                 - Show daily workflow"
    echo "  commands              - Show all available commands"
    echo "  shortcuts             - Show quick shortcuts"
    echo "  help                  - Show this help"
    echo ""
    echo "Examples:"
    echo "  $0 overview"
    echo "  $0 next"
    echo "  $0 start 15"
    echo "  $0 done 15"
    echo "  $0 search whisper"
    echo "  $0 analyze"
    echo "  $0 daily"
    echo ""
    echo "For detailed help on specific operations:"
    echo "  $0 commands"
    echo "  $0 shortcuts"
}

# Function to delegate to other scripts
delegate_to_script() {
    local script="$1"
    local command="$2"
    shift 2 || true
    
    local script_path="scripts/$script"
    if [ -f "$script_path" ]; then
        echo -e "${BLUE}🔄 Delegating to $script...${NC}"
        "$script_path" "$command" "$@"
    else
        echo -e "${RED}❌ Script $script not found${NC}"
        exit 1
    fi
}

# Main execution
check_taskmaster

CMD=${1:-help}
shift || true

case "$CMD" in
    overview)
        show_quick_overview
        ;;
    
    next)
        delegate_to_script "tm_status.sh" "next"
        ;;
    
    start)
        delegate_to_script "tm_workflow.sh" "start" "$@"
        ;;
    
    done)
        delegate_to_script "tm_workflow.sh" "complete" "$@"
        ;;
    
    search)
        delegate_to_script "tm_search.sh" "text" "$@"
        ;;
    
    analyze)
        delegate_to_script "tm_analyze.sh" "full"
        ;;
    
    daily)
        delegate_to_script "tm_workflow.sh" "daily"
        ;;
    
    commands)
        show_commands
        ;;
    
    shortcuts)
        show_shortcuts
        ;;
    
    help|h|*)
        show_help
        ;;
esac
