#!/bin/bash
# Taskmaster Status Checker
# Quick overview and detailed status information for Trax project

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 get quick stats
get_quick_stats() {
    print_header "📊 QUICK STATS"
    
    # Get task counts by status
    local total=$(task-master list 2>/dev/null | grep -c "^\s*[0-9]" || echo "0")
    local done=$(task-master list --status=done 2>/dev/null | grep -c "^\s*[0-9]" || echo "0")
    local pending=$(task-master list --status=pending 2>/dev/null | grep -c "^\s*[0-9]" || echo "0")
    local in_progress=$(task-master list --status=in-progress 2>/dev/null | grep -c "^\s*[0-9]" || 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
}

# Function to show next task
show_next_task() {
    print_header "🎯 NEXT TASK"
    
    local next_task=$(task-master next 2>/dev/null | head -20)
    if [ -n "$next_task" ]; then
        echo "$next_task"
    else
        echo -e "${YELLOW}No next task found or all tasks completed!${NC}"
    fi
}

# Function to show recent activity
show_recent_activity() {
    print_header "🕒 RECENT ACTIVITY"
    
    # Check for recent task changes in logs
    local log_file="$PROJECT_ROOT/logs/taskmaster_tracker.log"
    if [ -f "$log_file" ]; then
        echo -e "${BLUE}Recent task changes:${NC}"
        tail -10 "$log_file" | grep -E "(created|updated|status)" | tail -5 || echo "No recent activity found"
    else
        echo "No activity log found"
    fi
}

# Function to show pending tasks
show_pending_tasks() {
    print_header "📋 PENDING TASKS"
    
    local pending=$(task-master list --status=pending 2>/dev/null)
    if [ -n "$pending" ]; then
        echo "$pending"
    else
        echo -e "${GREEN}No pending tasks!${NC}"
    fi
}

# Function to show in-progress tasks
show_in_progress_tasks() {
    print_header "🚧 IN-PROGRESS TASKS"
    
    local in_progress=$(task-master list --status=in-progress 2>/dev/null)
    if [ -n "$in_progress" ]; then
        echo "$in_progress"
    else
        echo -e "${YELLOW}No tasks in progress${NC}"
    fi
}

# Function to show task details
show_task_details() {
    local task_id="$1"
    if [ -z "$task_id" ]; then
        echo -e "${RED}❌ Task ID required${NC}"
        echo "Usage: $0 details <task-id>"
        exit 1
    fi
    
    print_header "📄 TASK DETAILS: $task_id"
    
    local details=$(task-master show "$task_id" 2>/dev/null)
    if [ -n "$details" ]; then
        echo "$details"
    else
        echo -e "${RED}Task $task_id not found${NC}"
    fi
}

# Function to show pipeline overview
show_pipeline_overview() {
    print_header "🔄 PIPELINE OVERVIEW"
    
    # Use the Python script for pipeline-specific stats
    if [ -f "scripts/tm_trax.py" ]; then
        python3 scripts/tm_trax.py --stats 2>/dev/null || echo "Pipeline stats not available"
    else
        echo "Pipeline overview not available (tm_trax.py not found)"
    fi
}

# Function to show cache status
show_cache_status() {
    print_header "⚡ CACHE STATUS"
    
    local cache_dir="$PROJECT_ROOT/.taskmaster"
    if [ -d "$cache_dir" ]; then
        echo -e "${GREEN}✅ Taskmaster cache directory exists${NC}"
        
        # Check for tasks.json
        if [ -f "$cache_dir/tasks/tasks.json" ]; then
            local size=$(du -h "$cache_dir/tasks/tasks.json" | cut -f1)
            local modified=$(stat -f "%Sm" "$cache_dir/tasks/tasks.json" 2>/dev/null || stat -c "%y" "$cache_dir/tasks/tasks.json" 2>/dev/null)
            echo -e "${BLUE}📄 tasks.json: ${size} (modified: $modified)${NC}"
        else
            echo -e "${RED}❌ tasks.json not found${NC}"
        fi
        
        # Check for config
        if [ -f "$cache_dir/config.json" ]; then
            echo -e "${GREEN}✅ config.json exists${NC}"
        else
            echo -e "${YELLOW}⚠️  config.json not found${NC}"
        fi
    else
        echo -e "${RED}❌ Taskmaster cache directory not found${NC}"
    fi
}

# Function to show help
show_help() {
    echo -e "${CYAN}🚀 Taskmaster Status Checker${NC}"
    echo ""
    echo "Usage: $0 [command] [args]"
    echo ""
    echo "Commands:"
    echo "  stats              - Show quick statistics"
    echo "  next               - Show next available task"
    echo "  pending            - Show pending tasks"
    echo "  progress           - Show in-progress tasks"
    echo "  activity           - Show recent activity"
    echo "  pipeline           - Show pipeline overview"
    echo "  cache              - Show cache status"
    echo "  details <id>       - Show detailed task information"
    echo "  full               - Show comprehensive overview"
    echo "  help               - Show this help"
    echo ""
    echo "Examples:"
    echo "  $0 stats"
    echo "  $0 next"
    echo "  $0 details 15"
    echo "  $0 full"
}

# Main execution
check_taskmaster

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

case "$CMD" in
    stats)
        get_quick_stats
        ;;
    
    next)
        show_next_task
        ;;
    
    pending)
        show_pending_tasks
        ;;
    
    progress)
        show_in_progress_tasks
        ;;
    
    activity)
        show_recent_activity
        ;;
    
    pipeline)
        show_pipeline_overview
        ;;
    
    cache)
        show_cache_status
        ;;
    
    details)
        show_task_details "$1"
        ;;
    
    full)
        get_quick_stats
        echo ""
        show_next_task
        echo ""
        show_pending_tasks
        echo ""
        show_in_progress_tasks
        echo ""
        show_cache_status
        ;;
    
    help|h|*)
        show_help
        ;;
esac
