#!/bin/bash
# Taskmaster Search Helper
# Search tasks by various criteria 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 search by text
search_by_text() {
    local search_term="$1"
    if [ -z "$search_term" ]; then
        echo -e "${RED}❌ Search term required${NC}"
        echo "Usage: $0 text <search-term>"
        exit 1
    fi
    
    print_header "🔍 SEARCHING FOR: '$search_term'"
    
    # Use the Python script for better search capabilities
    if [ -f "scripts/tm_trax.py" ]; then
        python3 scripts/tm_trax.py --search "$search_term" 2>/dev/null || {
            echo "Python search failed, falling back to basic search..."
            task-master list | grep -i "$search_term" || echo "No matches found"
        }
    else
        echo "Basic search (install tm_trax.py for better search):"
        task-master list | grep -i "$search_term" || echo "No matches found"
    fi
}

# Function to search by status
search_by_status() {
    local status="$1"
    if [ -z "$status" ]; then
        echo -e "${RED}❌ Status required${NC}"
        echo "Usage: $0 status <status>"
        echo "Valid statuses: pending, in-progress, done, review, cancelled, deferred"
        exit 1
    fi
    
    print_header "📋 TASKS WITH STATUS: '$status'"
    
    local results=$(task-master list --status="$status" 2>/dev/null)
    if [ -n "$results" ]; then
        echo "$results"
    else
        echo -e "${YELLOW}No tasks found with status '$status'${NC}"
    fi
}

# Function to search by priority
search_by_priority() {
    local priority="$1"
    if [ -z "$priority" ]; then
        echo -e "${RED}❌ Priority required${NC}"
        echo "Usage: $0 priority <priority>"
        echo "Valid priorities: high, medium, low"
        exit 1
    fi
    
    print_header "🎯 TASKS WITH PRIORITY: '$priority'"
    
    # Get all tasks and filter by priority
    local all_tasks=$(task-master list 2>/dev/null)
    if [ -n "$all_tasks" ]; then
        echo "$all_tasks" | grep -i "priority.*$priority" || echo "No tasks found with priority '$priority'"
    else
        echo -e "${YELLOW}No tasks found${NC}"
    fi
}

# Function to search by pipeline version
search_by_pipeline() {
    local version="$1"
    if [ -z "$version" ]; then
        echo -e "${RED}❌ Pipeline version required${NC}"
        echo "Usage: $0 pipeline <version>"
        echo "Valid versions: v1, v2, v3, v4"
        exit 1
    fi
    
    print_header "🔄 PIPELINE VERSION: '$version'"
    
    # Use the Python script for pipeline-specific search
    if [ -f "scripts/tm_trax.py" ]; then
        python3 scripts/tm_trax.py --pipeline "$version" 2>/dev/null || echo "Pipeline search not available"
    else
        echo "Pipeline search requires tm_trax.py"
        # Fallback to basic search
        task-master list | grep -i "$version" || echo "No matches found"
    fi
}

# Function to search by task type
search_by_type() {
    local task_type="$1"
    if [ -z "$task_type" ]; then
        echo -e "${RED}❌ Task type required${NC}"
        echo "Usage: $0 type <type>"
        echo "Valid types: transcription, audio, enhancement, database, api, cli, test"
        exit 1
    fi
    
    print_header "📝 TASKS OF TYPE: '$task_type'"
    
    # Use the Python script for type-specific search
    if [ -f "scripts/tm_trax.py" ]; then
        python3 scripts/tm_trax.py --type "$task_type" 2>/dev/null || echo "Type search not available"
    else
        echo "Type search requires tm_trax.py"
        # Fallback to basic search
        task-master list | grep -i "$task_type" || echo "No matches found"
    fi
}

# Function to search by dependencies
search_by_dependencies() {
    local task_id="$1"
    if [ -z "$task_id" ]; then
        echo -e "${RED}❌ Task ID required${NC}"
        echo "Usage: $0 deps <task-id>"
        exit 1
    fi
    
    print_header "🔗 DEPENDENCIES FOR TASK: '$task_id'"
    
    local task_info=$(task-master show "$task_id" 2>/dev/null)
    if [ -n "$task_info" ]; then
        echo "$task_info" | grep -A 10 -B 5 "dependencies\|depends" || echo "No dependency information found"
    else
        echo -e "${RED}Task $task_id not found${NC}"
    fi
}

# Function to search by subtasks
search_by_subtasks() {
    local task_id="$1"
    if [ -z "$task_id" ]; then
        echo -e "${RED}❌ Task ID required${NC}"
        echo "Usage: $0 subtasks <task-id>"
        exit 1
    fi
    
    print_header "📋 SUBTASKS FOR TASK: '$task_id'"
    
    local task_info=$(task-master show "$task_id" 2>/dev/null)
    if [ -n "$task_info" ]; then
        echo "$task_info" | grep -A 20 "subtasks\|Subtasks" || echo "No subtasks found"
    else
        echo -e "${RED}Task $task_id not found${NC}"
    fi
}

# Function to search by date range (if available)
search_by_date() {
    local date_range="$1"
    if [ -z "$date_range" ]; then
        echo -e "${RED}❌ Date range required${NC}"
        echo "Usage: $0 date <date-range>"
        echo "Example: $0 date '2024-01-01 to 2024-01-31'"
        exit 1
    fi
    
    print_header "📅 TASKS BY DATE: '$date_range'"
    
    # This would require more sophisticated parsing of task metadata
    echo "Date-based search requires enhanced task metadata support"
    echo "Consider using the Python script for advanced date filtering"
}

# Function to show search help
show_help() {
    echo -e "${CYAN}🔍 Taskmaster Search Helper${NC}"
    echo ""
    echo "Usage: $0 [search-type] [search-term]"
    echo ""
    echo "Search Types:"
    echo "  text <term>        - Search by text in title/description"
    echo "  status <status>    - Search by task status"
    echo "  priority <level>   - Search by priority level"
    echo "  pipeline <version> - Search by pipeline version (v1-v4)"
    echo "  type <type>        - Search by task type"
    echo "  deps <task-id>     - Show dependencies for a task"
    echo "  subtasks <task-id> - Show subtasks for a task"
    echo "  date <range>       - Search by date range (if available)"
    echo "  help               - Show this help"
    echo ""
    echo "Examples:"
    echo "  $0 text whisper"
    echo "  $0 status pending"
    echo "  $0 priority high"
    echo "  $0 pipeline v1"
    echo "  $0 deps 15"
    echo "  $0 subtasks 15"
    echo ""
    echo "Valid Statuses: pending, in-progress, done, review, cancelled, deferred"
    echo "Valid Priorities: high, medium, low"
    echo "Valid Pipeline Versions: v1, v2, v3, v4"
    echo "Valid Task Types: transcription, audio, enhancement, database, api, cli, test"
}

# Main execution
check_taskmaster

SEARCH_TYPE=${1:-help}
SEARCH_TERM="$2"

case "$SEARCH_TYPE" in
    text)
        search_by_text "$SEARCH_TERM"
        ;;
    
    status)
        search_by_status "$SEARCH_TERM"
        ;;
    
    priority)
        search_by_priority "$SEARCH_TERM"
        ;;
    
    pipeline)
        search_by_pipeline "$SEARCH_TERM"
        ;;
    
    type)
        search_by_type "$SEARCH_TERM"
        ;;
    
    deps)
        search_by_dependencies "$SEARCH_TERM"
        ;;
    
    subtasks)
        search_by_subtasks "$SEARCH_TERM"
        ;;
    
    date)
        search_by_date "$SEARCH_TERM"
        ;;
    
    help|h|*)
        show_help
        ;;
esac
