#!/bin/bash
# Portfolio Journal Test Runner
# Usage: ./Scripts/run_tests.sh [options]
#
# Options:
#   --unit        Run unit tests only (default)
#   --ui          Run UI tests only
#   --all         Run all tests
#   --coverage    Generate code coverage report
#   --device      Specify simulator device (default: iPhone 17)
#   --help        Show this help message

set -e

# Configuration
PROJECT_PATH="PortfolioJournal.xcodeproj"
SCHEME="PortfolioJournal"
DEFAULT_DEVICE="iPhone 17"
DERIVED_DATA_PATH="$HOME/Library/Developer/Xcode/DerivedData/PortfolioJournal-Tests"

# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# Parse arguments
RUN_UNIT=true
RUN_UI=false
COVERAGE=false
DEVICE="$DEFAULT_DEVICE"

while [[ $# -gt 0 ]]; do
    case $1 in
        --unit)
            RUN_UNIT=true
            RUN_UI=false
            shift
            ;;
        --ui)
            RUN_UNIT=false
            RUN_UI=true
            shift
            ;;
        --all)
            RUN_UNIT=true
            RUN_UI=true
            shift
            ;;
        --coverage)
            COVERAGE=true
            shift
            ;;
        --device)
            DEVICE="$2"
            shift 2
            ;;
        --help|-h)
            echo "Portfolio Journal Test Runner"
            echo ""
            echo "Usage: ./Scripts/run_tests.sh [options]"
            echo ""
            echo "Options:"
            echo "  --unit        Run unit tests only (default)"
            echo "  --ui          Run UI tests only"
            echo "  --all         Run all tests"
            echo "  --coverage    Generate code coverage report"
            echo "  --device      Specify simulator device (default: iPhone 17)"
            echo "  --help        Show this help message"
            exit 0
            ;;
        *)
            echo "Unknown option: $1"
            exit 1
            ;;
    esac
done

# Print banner
echo -e "${BLUE}"
echo "╔══════════════════════════════════════════╗"
echo "║     Portfolio Journal Test Runner        ║"
echo "╚══════════════════════════════════════════╝"
echo -e "${NC}"

# Check if project exists
if [ ! -d "$PROJECT_PATH" ]; then
    echo -e "${RED}Error: Project not found at $PROJECT_PATH${NC}"
    echo "Make sure you're running this script from the project root directory."
    exit 1
fi

# Build test arguments
BUILD_ARGS=(
    -project "$PROJECT_PATH"
    -scheme "$SCHEME"
    -destination "platform=iOS Simulator,name=$DEVICE"
    -derivedDataPath "$DERIVED_DATA_PATH"
)

if [ "$COVERAGE" = true ]; then
    BUILD_ARGS+=(-enableCodeCoverage YES)
fi

# Function to run tests
run_tests() {
    local test_type=$1
    local test_target=$2

    echo -e "${YELLOW}Running $test_type tests...${NC}"
    echo "Device: $DEVICE"
    echo ""

    if xcodebuild test "${BUILD_ARGS[@]}" -only-testing:"$test_target" 2>&1 | xcpretty --color; then
        echo -e "${GREEN}✅ $test_type tests passed!${NC}"
        return 0
    else
        echo -e "${RED}❌ $test_type tests failed!${NC}"
        return 1
    fi
}

# Function to run all tests without filtering
run_all_tests() {
    echo -e "${YELLOW}Running all tests...${NC}"
    echo "Device: $DEVICE"
    echo ""

    if xcodebuild test "${BUILD_ARGS[@]}" 2>&1 | xcpretty --color; then
        echo -e "${GREEN}✅ All tests passed!${NC}"
        return 0
    else
        echo -e "${RED}❌ Some tests failed!${NC}"
        return 1
    fi
}

# Check if xcpretty is available
if ! command -v xcpretty &> /dev/null; then
    echo -e "${YELLOW}Warning: xcpretty not found. Install with: gem install xcpretty${NC}"
    echo "Running tests without pretty output..."
    echo ""

    # Run without xcpretty
    run_tests_raw() {
        if [ "$RUN_UNIT" = true ] && [ "$RUN_UI" = true ]; then
            xcodebuild test "${BUILD_ARGS[@]}"
        elif [ "$RUN_UNIT" = true ]; then
            xcodebuild test "${BUILD_ARGS[@]}" -only-testing:PortfolioJournalTests
        elif [ "$RUN_UI" = true ]; then
            xcodebuild test "${BUILD_ARGS[@]}" -only-testing:PortfolioJournalUITests
        fi
    }

    if run_tests_raw; then
        echo -e "${GREEN}✅ Tests passed!${NC}"
        exit 0
    else
        echo -e "${RED}❌ Tests failed!${NC}"
        exit 1
    fi
fi

# Run tests
EXIT_CODE=0

if [ "$RUN_UNIT" = true ] && [ "$RUN_UI" = true ]; then
    run_all_tests || EXIT_CODE=1
elif [ "$RUN_UNIT" = true ]; then
    run_tests "Unit" "PortfolioJournalTests" || EXIT_CODE=1
elif [ "$RUN_UI" = true ]; then
    run_tests "UI" "PortfolioJournalUITests" || EXIT_CODE=1
fi

# Generate coverage report if requested
if [ "$COVERAGE" = true ] && [ $EXIT_CODE -eq 0 ]; then
    echo ""
    echo -e "${YELLOW}Generating code coverage report...${NC}"

    COVERAGE_PATH="$DERIVED_DATA_PATH/Build/ProfileData"

    if [ -d "$COVERAGE_PATH" ]; then
        # Find the profdata file
        PROFDATA=$(find "$COVERAGE_PATH" -name "*.profdata" | head -1)

        if [ -n "$PROFDATA" ]; then
            echo "Coverage data found at: $PROFDATA"
            echo ""
            echo "To view detailed coverage:"
            echo "  xcrun llvm-cov report \\"
            echo "    \"$DERIVED_DATA_PATH/Build/Products/Debug-iphonesimulator/PortfolioJournal.app/PortfolioJournal\" \\"
            echo "    -instr-profile=\"$PROFDATA\""
        else
            echo -e "${YELLOW}No coverage data found. Make sure tests ran successfully.${NC}"
        fi
    else
        echo -e "${YELLOW}Coverage directory not found.${NC}"
    fi
fi

echo ""
if [ $EXIT_CODE -eq 0 ]; then
    echo -e "${GREEN}════════════════════════════════════════════${NC}"
    echo -e "${GREEN}  All tests completed successfully! 🎉      ${NC}"
    echo -e "${GREEN}════════════════════════════════════════════${NC}"
else
    echo -e "${RED}════════════════════════════════════════════${NC}"
    echo -e "${RED}  Some tests failed. Please review above.   ${NC}"
    echo -e "${RED}════════════════════════════════════════════${NC}"
fi

exit $EXIT_CODE
