#!/bin/bash
# Taskmaster Analysis Helper
# Analyze task complexity and project insights 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 analyze task complexity
analyze_complexity() {
    print_header "🔍 ANALYZING TASK COMPLEXITY"
    
    echo -e "${BLUE}📊 Running complexity analysis...${NC}"
    echo "This may take a moment..."
    
    # Run complexity analysis
    task-master analyze-complexity --research 2>/dev/null || {
        echo -e "${YELLOW}⚠️  Research-based analysis failed, trying basic analysis...${NC}"
        task-master analyze-complexity 2>/dev/null || {
            echo -e "${RED}❌ Complexity analysis failed${NC}"
            exit 1
        }
    }
    
    echo -e "${GREEN}✅ Complexity analysis completed!${NC}"
    echo ""
    echo -e "${CYAN}📋 View the report with: $0 report${NC}"
}

# Function to show complexity report
show_complexity_report() {
    print_header "📊 COMPLEXITY REPORT"
    
    echo -e "${BLUE}📄 Loading complexity report...${NC}"
    
    # Show the complexity report
    task-master complexity-report 2>/dev/null || {
        echo -e "${RED}❌ Complexity report not found${NC}"
        echo "Run '$0 analyze' first to generate the report"
        exit 1
    }
}

# Function to analyze dependencies
analyze_dependencies() {
    print_header "🔗 DEPENDENCY ANALYSIS"
    
    echo -e "${BLUE}🔍 Checking task dependencies...${NC}"
    
    # Validate dependencies
    task-master validate-dependencies 2>/dev/null || {
        echo -e "${YELLOW}⚠️  Dependency validation failed${NC}"
        exit 1
    }
    
    echo -e "${GREEN}✅ Dependencies validated!${NC}"
    
    # Show dependency statistics
    echo ""
    echo -e "${CYAN}📊 Dependency Statistics:${NC}"
    
    # Count tasks with dependencies
    local all_tasks=$(task-master list 2>/dev/null)
    local total_tasks=$(echo "$all_tasks" | grep -c "^\s*[0-9]" || echo "0")
    local tasks_with_deps=$(echo "$all_tasks" | grep -c "dependencies" || echo "0")
    
    echo -e "${BLUE}Total tasks: $total_tasks${NC}"
    echo -e "${BLUE}Tasks with dependencies: $tasks_with_deps${NC}"
    
    if [ "$total_tasks" -gt 0 ]; then
        local dep_percentage=$((tasks_with_deps * 100 / total_tasks))
        echo -e "${CYAN}Dependency coverage: ${dep_percentage}%${NC}"
    fi
}

# Function to analyze task distribution
analyze_distribution() {
    print_header "📈 TASK DISTRIBUTION ANALYSIS"
    
    echo -e "${BLUE}📊 Analyzing task distribution...${NC}"
    
    # 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")
    local review=$(task-master list --status=review 2>/dev/null | grep -c "^\s*[0-9]" || echo "0")
    local deferred=$(task-master list --status=deferred 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}👀 Review: $review${NC}"
    echo -e "${RED}⏸️  Deferred: $deferred${NC}"
    echo -e "${CYAN}📊 Total: $total${NC}"
    
    if [ "$total" -gt 0 ]; then
        echo ""
        echo -e "${CYAN}📈 Distribution Percentages:${NC}"
        echo -e "${GREEN}Done: $((done * 100 / total))%${NC}"
        echo -e "${YELLOW}In Progress: $((in_progress * 100 / total))%${NC}"
        echo -e "${BLUE}Pending: $((pending * 100 / total))%${NC}"
        echo -e "${MAGENTA}Review: $((review * 100 / total))%${NC}"
        echo -e "${RED}Deferred: $((deferred * 100 / total))%${NC}"
    fi
}

# Function to analyze pipeline progress
analyze_pipeline() {
    print_header "🔄 PIPELINE PROGRESS ANALYSIS"
    
    echo -e "${BLUE}📊 Analyzing pipeline versions...${NC}"
    
    # Use the Python script for pipeline analysis
    if [ -f "scripts/tm_trax.py" ]; then
        python3 scripts/tm_trax.py --stats 2>/dev/null || {
            echo -e "${YELLOW}⚠️  Pipeline analysis not available${NC}"
            echo "Basic pipeline search:"
            for version in v1 v2 v3 v4; do
                local count=$(task-master list 2>/dev/null | grep -i "$version" | wc -l)
                echo -e "${BLUE}$version: $count tasks${NC}"
            done
        }
    else
        echo "Pipeline analysis requires tm_trax.py"
        # Basic pipeline search
        for version in v1 v2 v3 v4; do
            local count=$(task-master list 2>/dev/null | grep -i "$version" | wc -l)
            echo -e "${BLUE}$version: $count tasks${NC}"
        done
    fi
}

# Function to analyze bottlenecks
analyze_bottlenecks() {
    print_header "🚧 BOTTLENECK ANALYSIS"
    
    echo -e "${BLUE}🔍 Identifying potential bottlenecks...${NC}"
    
    # Find tasks with many dependencies
    echo -e "${CYAN}📋 Tasks with many dependencies (potential bottlenecks):${NC}"
    task-master list 2>/dev/null | grep -E "dependencies.*[0-9]{2,}" || echo "No high-dependency tasks found"
    
    echo ""
    echo -e "${CYAN}📋 Tasks in review (potential blockers):${NC}"
    task-master list --status=review 2>/dev/null || echo "No tasks in review"
    
    echo ""
    echo -e "${CYAN}📋 Deferred tasks (potential issues):${NC}"
    task-master list --status=deferred 2>/dev/null || echo "No deferred tasks"
    
    echo ""
    echo -e "${CYAN}📋 Long-running in-progress tasks:${NC}"
    task-master list --status=in-progress 2>/dev/null || echo "No in-progress tasks"
}

# Function to generate insights
generate_insights() {
    print_header "💡 PROJECT INSIGHTS"
    
    echo -e "${BLUE}🧠 Generating project insights...${NC}"
    
    # Get basic stats
    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")
    
    echo -e "${CYAN}📊 Key Metrics:${NC}"
    echo -e "${BLUE}Total tasks: $total${NC}"
    echo -e "${GREEN}Completed: $done${NC}"
    echo -e "${BLUE}Remaining: $pending${NC}"
    
    if [ "$total" -gt 0 ]; then
        local completion=$((done * 100 / total))
        local remaining=$((pending * 100 / total))
        
        echo ""
        echo -e "${CYAN}📈 Progress Insights:${NC}"
        echo -e "${GREEN}Project completion: ${completion}%${NC}"
        echo -e "${BLUE}Work remaining: ${remaining}%${NC}"
        
        if [ "$completion" -gt 75 ]; then
            echo -e "${GREEN}🎉 Great progress! Project is in final stages${NC}"
        elif [ "$completion" -gt 50 ]; then
            echo -e "${YELLOW}📈 Good progress! Project is past halfway${NC}"
        elif [ "$completion" -gt 25 ]; then
            echo -e "${BLUE}🚀 Steady progress! Project is building momentum${NC}"
        else
            echo -e "${CYAN}🌱 Early stages! Focus on foundational tasks${NC}"
        fi
    fi
    
    echo ""
    echo -e "${CYAN}🎯 Recommendations:${NC}"
    
    # Check for next task
    local next_task=$(task-master next 2>/dev/null | head -5)
    if [ -n "$next_task" ]; then
        echo -e "${BLUE}Next priority: Focus on the next available task${NC}"
    fi
    
    # Check for blocked tasks
    local blocked=$(task-master list --status=deferred 2>/dev/null | wc -l)
    if [ "$blocked" -gt 0 ]; then
        echo -e "${YELLOW}⚠️  Address $blocked deferred tasks to unblock progress${NC}"
    fi
    
    # Check for review tasks
    local review=$(task-master list --status=review 2>/dev/null | wc -l)
    if [ "$review" -gt 0 ]; then
        echo -e "${MAGENTA}👀 Review $review tasks to complete them${NC}"
    fi
}

# Function to show analysis help
show_help() {
    echo -e "${CYAN}🔍 Taskmaster Analysis Helper${NC}"
    echo ""
    echo "Usage: $0 [command] [args]"
    echo ""
    echo "Analysis Commands:"
    echo "  analyze             - Run complexity analysis"
    echo "  report              - Show complexity report"
    echo "  dependencies        - Analyze task dependencies"
    echo "  distribution        - Analyze task distribution"
    echo "  pipeline            - Analyze pipeline progress"
    echo "  bottlenecks         - Identify potential bottlenecks"
    echo "  insights            - Generate project insights"
    echo "  full                - Run comprehensive analysis"
    echo "  help                - Show this help"
    echo ""
    echo "Examples:"
    echo "  $0 analyze"
    echo "  $0 report"
    echo "  $0 dependencies"
    echo "  $0 insights"
    echo "  $0 full"
    echo ""
    echo "Analysis Tips:"
    echo "  - Run 'analyze' first to generate complexity data"
    echo "  - Use 'report' to view detailed complexity breakdown"
    echo "  - Use 'insights' for high-level project recommendations"
    echo "  - Use 'full' for comprehensive project analysis"
}

# Main execution
check_taskmaster

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

case "$CMD" in
    analyze)
        analyze_complexity
        ;;
    
    report)
        show_complexity_report
        ;;
    
    dependencies)
        analyze_dependencies
        ;;
    
    distribution)
        analyze_distribution
        ;;
    
    pipeline)
        analyze_pipeline
        ;;
    
    bottlenecks)
        analyze_bottlenecks
        ;;
    
    insights)
        generate_insights
        ;;
    
    full)
        analyze_complexity
        echo ""
        show_complexity_report
        echo ""
        analyze_dependencies
        echo ""
        analyze_distribution
        echo ""
        analyze_pipeline
        echo ""
        analyze_bottlenecks
        echo ""
        generate_insights
        ;;
    
    help|h|*)
        show_help
        ;;
esac
