#!/bin/bash
set -euo pipefail

SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" &> /dev/null && pwd )"
WHATSDIRTY_SCRIPT="$SCRIPT_DIR/whatsdirty"
CONFIG_FILE="$HOME/.config/whatsdirty.conf"
BACKUP_FILE=""
TEST_PASSED=true

# Colors for output
GREEN='\033[0;32m'
RED='\033[0;31m'
NC='\033[0m' # No Color

# Function to print test results
print_test() {
    local test_name="$1"
    local result="$2"
    if [ "$result" = "PASS" ]; then
        echo -e "${GREEN}✓${NC} $test_name"
    else
        echo -e "${RED}✗${NC} $test_name"
        TEST_PASSED=false
    fi
}

# Function to cleanup and restore
CLEANED=false
cleanup() {
    if [ "$CLEANED" = true ]; then
        return
    fi
    CLEANED=true
    if [ -n "$BACKUP_FILE" ] && [ -f "$BACKUP_FILE" ]; then
        cp "$BACKUP_FILE" "$CONFIG_FILE"
        rm -f "$BACKUP_FILE"
    elif [ -n "$BACKUP_FILE" ]; then
        # Original didn't exist, so remove the created one
        rm -f "$CONFIG_FILE"
    fi
}

# Set up trap to restore config on exit
trap cleanup EXIT

echo "Testing whatsdirty configuration behavior..."
echo "Working directory: $(pwd)"
echo "Script path: $WHATSDIRTY_SCRIPT"
echo "Config file: $CONFIG_FILE"
echo

# Backup existing config if it exists
if [ -f "$CONFIG_FILE" ]; then
    BACKUP_FILE=$(mktemp)
    cp "$CONFIG_FILE" "$BACKUP_FILE"
else
    # Mark that we need to remove the config file on cleanup
    BACKUP_FILE="NONE_EXISTED"
fi

# Remove config to start fresh
rm -f "$CONFIG_FILE"

# Test 1: Running without arguments and no config should fail
echo "Test 1: First run without arguments (should fail)"
OUTPUT=$("$WHATSDIRTY_SCRIPT" 2>&1 || true)
if echo "$OUTPUT" | grep -q "No directory specified and no saved directory found"; then
    print_test "First run without args shows error" "PASS"
else
    print_test "First run without args shows error" "FAIL"
    echo "  Expected: 'No directory specified and no saved directory found'"
    echo "  Got: $OUTPUT"
fi

# Test 2: Running with a valid directory should save config
echo -e "\nTest 2: First run with directory argument"
# Use a directory that should exist in most environments
TEST_DIR="/tmp"
echo "  Testing with directory: $TEST_DIR"
if [ -d "$TEST_DIR" ]; then
    echo "  Directory exists, running script..."
    SCRIPT_OUTPUT=$("$WHATSDIRTY_SCRIPT" "$TEST_DIR" 2>&1)
    SCRIPT_EXIT_CODE=$?
    echo "  Script exit code: $SCRIPT_EXIT_CODE"
    if [ $SCRIPT_EXIT_CODE -eq 0 ] && [ -f "$CONFIG_FILE" ] && [ "$(cat "$CONFIG_FILE")" = "$TEST_DIR" ]; then
        print_test "Directory saved to config" "PASS"
    else
        print_test "Directory saved to config" "FAIL"
        echo "  Expected config to contain: $TEST_DIR"
        echo "  Config file exists: $([ -f "$CONFIG_FILE" ] && echo "yes" || echo "no")"
        [ -f "$CONFIG_FILE" ] && echo "  Config contains: $(cat "$CONFIG_FILE")"
        echo "  Script output: $SCRIPT_OUTPUT"
    fi
else
    print_test "Directory saved to config" "SKIP (test directory not found)"
fi

# Test 3: Running without arguments should use saved directory
echo -e "\nTest 3: Subsequent run without arguments"
OUTPUT=$("$WHATSDIRTY_SCRIPT" 2>&1 || true)
# Should not contain error message about no directory
if ! echo "$OUTPUT" | grep -q "Error:" && [ -f "$CONFIG_FILE" ]; then
    print_test "Uses saved directory from config" "PASS"
else
    print_test "Uses saved directory from config" "FAIL"
    echo "  Output: $OUTPUT"
fi

# Test 4: Running with new directory should update config
echo -e "\nTest 4: Run with different directory"
# Use the parent directory (should exist)
NEW_TEST_DIR="$SCRIPT_DIR/.."
if [ -d "$NEW_TEST_DIR" ]; then
    CANONICAL_DIR=$(cd "$NEW_TEST_DIR" && pwd)
    "$WHATSDIRTY_SCRIPT" "$NEW_TEST_DIR" > /dev/null 2>&1
    if [ -f "$CONFIG_FILE" ] && [ "$(cat "$CONFIG_FILE")" = "$CANONICAL_DIR" ]; then
        print_test "Config updated with new directory" "PASS"
    else
        print_test "Config updated with new directory" "FAIL"
        echo "  Expected: $CANONICAL_DIR"
        echo "  Got: $(cat "$CONFIG_FILE" 2>/dev/null || echo "file not found")"
    fi
else
    print_test "Config updated with new directory" "SKIP (test directory not found)"
fi

# Test 5: Invalid directory should fail
echo -e "\nTest 5: Invalid directory handling"
OUTPUT=$("$WHATSDIRTY_SCRIPT" "/nonexistent/directory" 2>&1 || true)
if echo "$OUTPUT" | grep -q "Directory '/nonexistent/directory' not found"; then
    print_test "Invalid directory shows error" "PASS"
else
    print_test "Invalid directory shows error" "FAIL"
    echo "  Expected: 'Directory '/nonexistent/directory' not found'"
    echo "  Got: $OUTPUT"
fi

# Test 6: Saved directory that no longer exists
echo -e "\nTest 6: Saved directory that no longer exists"
mkdir -p "$(dirname "$CONFIG_FILE")"
echo "/nonexistent/saved/directory" > "$CONFIG_FILE"
OUTPUT=$("$WHATSDIRTY_SCRIPT" 2>&1 || true)
if echo "$OUTPUT" | grep -q "no longer exists"; then
    # Check that config was removed
    if [ ! -f "$CONFIG_FILE" ]; then
        print_test "Handles deleted saved directory" "PASS"
    else
        print_test "Handles deleted saved directory" "FAIL (config not cleaned up)"
    fi
else
    print_test "Handles deleted saved directory" "FAIL"
    echo "  Expected message about directory no longer existing"
    echo "  Got: $OUTPUT"
fi

cleanup

# Summary
echo
if [ "$TEST_PASSED" = true ]; then
    echo -e "${GREEN}All tests passed!${NC}"
    exit 0
else
    echo -e "${RED}Some tests failed!${NC}"
    exit 1
fi

