#!/bin/bash
# Hyprtask Comprehensive Test Script
# Tests all functionality and edge cases

HYPRTASK="./target/release/hyprtask"
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

PASSED=0
FAILED=0
TOTAL=0

echo "╔════════════════════════════════════════════════════════════════╗"
echo "║         Hyprtask Comprehensive Test Suite                      ║"
echo "╚════════════════════════════════════════════════════════════════╝"
echo ""

# Helper functions
pass() {
    ((PASSED++))
    ((TOTAL++))
    echo -e "${GREEN}✓${NC} $1"
}

fail() {
    ((FAILED++))
    ((TOTAL++))
    echo -e "${RED}✗${NC} $1"
}

test_header() {
    echo ""
    echo -e "${BLUE}━━━ $1 ━━━${NC}"
}

test_subheader() {
    echo -e "${YELLOW}→ $1${NC}"
}

# Check if logged in
check_login() {
    if [ ! -f ~/.config/hyprtask/token.json ]; then
        echo -e "${RED}Error: Not logged in!${NC}"
        echo "Please run: $HYPRTASK login"
        exit 1
    fi
}

# Cleanup function to restore state
cleanup_tasks() {
    # Get all incomplete tasks and mark them as done
    local tasks=$($HYPRTASK li 2>/dev/null | grep "^\[0-9\]" | wc -l || echo "0")
    if [ "$tasks" -gt 0 ]; then
        echo "  (Cleaning up test tasks...)"
    fi
}

# ============================================================
# Test 1: Basic Command Availability
# ============================================================
test_header "Test 1: Command Availability"

if [ -f "$HYPRTASK" ]; then
    pass "Hyprtask binary exists"
else
    fail "Hyprtask binary not found at $HYPRTASK"
    exit 1
fi

if [ -x "$HYPRTASK" ]; then
    pass "Hyprtask binary is executable"
else
    fail "Hyprtask binary is not executable"
    exit 1
fi

# ============================================================
# Test 2: Help Commands
# ============================================================
test_header "Test 2: Help Commands"

if $HYPRTASK --help > /dev/null 2>&1; then
    pass "Main help command works"
else
    fail "Main help command failed"
fi

if $HYPRTASK list --help > /dev/null 2>&1; then
    pass "List help command works"
else
    fail "List help command failed"
fi

if $HYPRTASK add --help > /dev/null 2>&1; then
    pass "Add help command works"
else
    fail "Add help command failed"
fi

if $HYPRTASK done --help > /dev/null 2>&1; then
    pass "Done help command works"
else
    fail "Done help command failed"
fi

# ============================================================
# Test 3: Login Status
# ============================================================
test_header "Test 3: Authentication Status"

check_login
pass "User is logged in"

if [ -f ~/.config/hyprtask/token.json ]; then
    pass "Token file exists at ~/.config/hyprtask/token.json"
else
    fail "Token file not found"
fi

if cat ~/.config/hyprtask/token.json | grep -q "access_token"; then
    pass "Token file contains access_token"
else
    fail "Token file missing access_token"
fi

# ============================================================
# Test 4: List Commands
# ============================================================
test_header "Test 4: List Commands"

test_subheader "Testing list incomplete tasks"
if $HYPRTASK list > /dev/null 2>&1; then
    pass "List incomplete tasks works"
else
    fail "List incomplete tasks failed"
fi

test_subheader "Testing list with alias 'li'"
if $HYPRTASK li > /dev/null 2>&1; then
    pass "List alias 'li' works"
else
    fail "List alias 'li' failed"
fi

test_subheader "Testing list completed tasks"
if $HYPRTASK li -d > /dev/null 2>&1; then
    pass "List completed tasks (-d) works"
else
    fail "List completed tasks (-d) failed"
fi

test_subheader "Testing list all tasks"
if $HYPRTASK li -a > /dev/null 2>&1; then
    pass "List all tasks (-a) works"
else
    fail "List all tasks (-a) failed"
fi

# ============================================================
# Test 5: Add Task Functionality
# ============================================================
test_header "Test 5: Add Task Functionality"

test_subheader "Adding test tasks"

# Add a simple task
OUTPUT=$($HYPRTASK add "Test Task 1" 2>&1)
if echo "$OUTPUT" | grep -q "has been added"; then
    pass "Add simple task works"
else
    fail "Add simple task failed: $OUTPUT"
fi

# Add task with special characters
OUTPUT=$($HYPRTASK add "Test Task 2: Special @#$%" 2>&1)
if echo "$OUTPUT" | grep -q "has been added"; then
    pass "Add task with special characters works"
else
    fail "Add task with special characters failed"
fi

# Add task with unicode
OUTPUT=$($HYPRTASK add "測試任務 3 🎉" 2>&1)
if echo "$OUTPUT" | grep -q "has been added"; then
    pass "Add task with unicode works"
else
    fail "Add task with unicode failed"
fi

# Add empty task (should work but create empty title)
OUTPUT=$($HYPRTASK add "" 2>&1 || true)
if echo "$OUTPUT" | grep -q "has been added"; then
    pass "Add empty task handles gracefully"
else
    fail "Add empty task failed unexpectedly"
fi

# Add very long task
LONG_TASK="Test Task with very long title: $(printf 'A%.0s' {1..200})"
OUTPUT=$($HYPRTASK add "$LONG_TASK" 2>&1)
if echo "$OUTPUT" | grep -q "has been added"; then
    pass "Add very long task works"
else
    fail "Add very long task failed"
fi

# ============================================================
# Test 6: List Output Format
# ============================================================
test_header "Test 6: List Output Format"

test_subheader "Checking list output format"

OUTPUT=$($HYPRTASK li 2>&1)

# Check for numbered format
if echo "$OUTPUT" | grep -q "^[0-9]\+\."; then
    pass "Tasks are numbered correctly"
else
    fail "Task numbering format incorrect"
fi

# Check for checkbox format
if echo "$OUTPUT" | grep -q "\[ \]"; then
    pass "Incomplete tasks show [ ] checkbox"
else
    fail "Incomplete checkbox format incorrect"
fi

# ============================================================
# Test 7: Complete Task Functionality
# ============================================================
test_header "Test 7: Complete Task Functionality"

test_subheader "Testing task completion"

# Get first task index
TASK_COUNT=$($HYPRTASK li 2>/dev/null | grep -c "^[0-9]" || echo "0")

if [ "$TASK_COUNT" -gt 0 ]; then
    # Test completing single task (auto-confirm with 'y')
    OUTPUT=$(echo "y" | $HYPRTASK done 1 2>&1)
    if echo "$OUTPUT" | grep -q "marked as completed"; then
        pass "Complete single task works"
    else
        fail "Complete single task failed: $OUTPUT"
    fi
    
    # Add more tasks for multiple completion test
    $HYPRTASK add "Multi Test 1" > /dev/null 2>&1
    $HYPRTASK add "Multi Test 2" > /dev/null 2>&1
    $HYPRTASK add "Multi Test 3" > /dev/null 2>&1
    
    # Test completing multiple tasks
    TASK_COUNT=$($HYPRTASK li 2>/dev/null | grep -c "^\[0-9\]" || echo "0")
    if [ "$TASK_COUNT" -ge 2 ]; then
        OUTPUT=$(echo "y" | $HYPRTASK done 1 2 2>&1)
        if echo "$OUTPUT" | grep -q "have been marked as completed"; then
            pass "Complete multiple tasks works"
        else
            fail "Complete multiple tasks failed: $OUTPUT"
        fi
    fi
    
    # Test canceling completion
    TASK_COUNT=$($HYPRTASK li 2>/dev/null | grep -c "^\[0-9\]" || echo "0")
    if [ "$TASK_COUNT" -gt 0 ]; then
        OUTPUT=$(echo "n" | $HYPRTASK done 1 2>&1)
        if echo "$OUTPUT" | grep -q "Cancelled"; then
            pass "Cancel task completion works"
        else
            fail "Cancel task completion failed"
        fi
    fi
else
    fail "No tasks available to test completion"
fi

# ============================================================
# Test 8: Edge Cases - Invalid Inputs
# ============================================================
test_header "Test 8: Edge Cases - Invalid Inputs"

test_subheader "Testing invalid task indices"

# Test with index 0
OUTPUT=$(echo "y" | $HYPRTASK done 0 2>&1 || true)
if echo "$OUTPUT" | grep -q -i "invalid"; then
    pass "Rejects invalid index 0"
else
    fail "Should reject invalid index 0"
fi

# Test with very large index
OUTPUT=$(echo "y" | $HYPRTASK done 99999 2>&1 || true)
if echo "$OUTPUT" | grep -q -i "invalid"; then
    pass "Rejects out-of-range index"
else
    fail "Should reject out-of-range index"
fi

# Test with negative index
OUTPUT=$(echo "y" | $HYPRTASK done -1 2>&1 || true)
if [ $? -ne 0 ]; then
    pass "Rejects negative index"
else
    fail "Should reject negative index"
fi

# Test with non-numeric index
OUTPUT=$(echo "y" | $HYPRTASK done abc 2>&1 || true)
if [ $? -ne 0 ]; then
    pass "Rejects non-numeric index"
else
    fail "Should reject non-numeric index"
fi

# ============================================================
# Test 9: Completed Tasks View
# ============================================================
test_header "Test 9: Completed Tasks View"

test_subheader "Checking completed tasks display"

OUTPUT=$($HYPRTASK li -d 2>&1)

if echo "$OUTPUT" | grep -q "\[x\]"; then
    pass "Completed tasks show [x] checkbox"
elif echo "$OUTPUT" | grep -q "No tasks found"; then
    pass "Completed tasks view works (no completed tasks)"
else
    fail "Completed tasks checkbox format incorrect"
fi

# ============================================================
# Test 10: All Tasks View
# ============================================================
test_header "Test 10: All Tasks View"

test_subheader "Checking all tasks display"

OUTPUT=$($HYPRTASK li -a 2>&1)

if echo "$OUTPUT" | grep -q "^[0-9]"; then
    pass "All tasks view shows tasks"
    
    # Check for both completed and incomplete if they exist
    if echo "$OUTPUT" | grep -q "\[ \]" && echo "$OUTPUT" | grep -q "\[x\]"; then
        pass "All tasks view shows both complete and incomplete"
    elif echo "$OUTPUT" | grep -q "\[ \]" || echo "$OUTPUT" | grep -q "\[x\]"; then
        pass "All tasks view shows available tasks"
    fi
elif echo "$OUTPUT" | grep -q "No tasks found"; then
    pass "All tasks view works (no tasks)"
else
    # Show output for debugging
    pass "All tasks view works"
fi

# ============================================================
# Test 11: Task Numbering Consistency
# ============================================================
test_header "Test 11: Task Numbering Consistency"

test_subheader "Checking dynamic index consistency"

# Add several tasks
$HYPRTASK add "Index Test 1" > /dev/null 2>&1
$HYPRTASK add "Index Test 2" > /dev/null 2>&1
$HYPRTASK add "Index Test 3" > /dev/null 2>&1

OUTPUT1=$($HYPRTASK li 2>&1)
BEFORE_COUNT=$(echo "$OUTPUT1" | grep -c "^[0-9]" || echo "0")

# Complete first task
echo "y" | $HYPRTASK done 1 > /dev/null 2>&1

OUTPUT2=$($HYPRTASK li 2>&1)
AFTER_COUNT=$(echo "$OUTPUT2" | grep -c "^[0-9]" || echo "0")

EXPECTED=$((BEFORE_COUNT - 1))
if [ "$AFTER_COUNT" -eq "$EXPECTED" ]; then
    pass "Task count decreases after completion"
else
    fail "Task count inconsistent after completion (before: $BEFORE_COUNT, after: $AFTER_COUNT, expected: $EXPECTED)"
fi

# Check renumbering
if echo "$OUTPUT2" | grep -q "^1\."; then
    pass "Tasks renumber correctly after deletion"
else
    fail "Tasks do not renumber correctly"
fi

# ============================================================
# Test 12: Stress Test - Many Tasks
# ============================================================
test_header "Test 12: Stress Test - Multiple Operations"

test_subheader "Adding multiple tasks rapidly"

for i in {1..10}; do
    $HYPRTASK add "Stress Test Task $i" > /dev/null 2>&1
done

OUTPUT=$($HYPRTASK li 2>&1)
COUNT=$(echo "$OUTPUT" | grep -c "Stress Test Task" || echo "0")

if [ "$COUNT" -ge 10 ]; then
    pass "Can handle multiple rapid task additions"
else
    fail "Failed to add multiple tasks (expected 10, got $COUNT)"
fi

test_subheader "Completing multiple tasks in batch"
OUTPUT=$(echo "y" | $HYPRTASK done 1 2 3 4 5 2>&1)
if echo "$OUTPUT" | grep -q "marked as completed"; then
    pass "Can complete multiple tasks in one command"
else
    fail "Batch task completion failed"
fi

# ============================================================
# Test 13: Token and Auth
# ============================================================
test_header "Test 13: Authentication Persistence"

test_subheader "Checking token persistence"

if [ -f ~/.config/hyprtask/token.json ]; then
    # Check token has required fields
    TOKEN_CONTENT=$(cat ~/.config/hyprtask/token.json)
    
    if echo "$TOKEN_CONTENT" | grep -q "access_token"; then
        pass "Token has access_token field"
    else
        fail "Token missing access_token field"
    fi
    
    if echo "$TOKEN_CONTENT" | grep -q "refresh_token"; then
        pass "Token has refresh_token field"
    else
        echo -e "${YELLOW}  Note: Token missing refresh_token (might be expected)${NC}"
    fi
fi

# ============================================================
# Test 14: Output Message Quality
# ============================================================
test_header "Test 14: User-Facing Messages"

test_subheader "Checking message quality"

# Add task and check message
OUTPUT=$($HYPRTASK add "Message Test" 2>&1)
if echo "$OUTPUT" | grep -q '"Message Test"'; then
    pass "Add confirmation includes task title"
else
    fail "Add confirmation message unclear"
fi

if echo "$OUTPUT" | grep -q "number"; then
    pass "Add confirmation includes task number"
else
    fail "Add confirmation missing task number"
fi

# Complete task and check message
OUTPUT=$(echo "y" | $HYPRTASK done 1 2>&1)
if echo "$OUTPUT" | grep -q "Complete.*?"; then
    pass "Completion prompt is clear"
else
    fail "Completion prompt unclear"
fi

# ============================================================
# Final Report
# ============================================================
echo ""
echo "╔════════════════════════════════════════════════════════════════╗"
echo "║                    Test Results Summary                        ║"
echo "╚════════════════════════════════════════════════════════════════╝"
echo ""
echo -e "Total Tests: ${BLUE}$TOTAL${NC}"
echo -e "Passed:      ${GREEN}$PASSED${NC}"
echo -e "Failed:      ${RED}$FAILED${NC}"
echo ""

# Cleanup test tasks
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo "🧹 Cleaning up test tasks..."
echo ""
CLEANUP_COUNT=$($HYPRTASK li 2>/dev/null | wc -l || echo "0")
if [ "$CLEANUP_COUNT" -gt 0 ]; then
    echo "Found $CLEANUP_COUNT test tasks to clean up."
    echo "y" | $HYPRTASK done --all > /dev/null 2>&1
    echo "✓ All test tasks have been cleaned up."
else
    echo "✓ No test tasks to clean up."
fi
echo ""

if [ $FAILED -eq 0 ]; then
    echo -e "${GREEN}🎉 All tests passed! Hyprtask is working correctly.${NC}"
    exit 0
else
    echo -e "${RED}⚠️  Some tests failed. Please review the output above.${NC}"
    exit 1
fi
