#!/bin/bash
#
# Pre-Deployment Checklist for Screenshare Bot
# Task #119 Stream A - Production Deployment & Monitoring
#
# This script validates that all requirements are met before deploying to Railway.
# It checks code quality, dependencies, configuration, and documentation.
#
# Usage:
#   ./scripts/pre_deployment_check.sh
#
# Exit codes:
#   0 - All checks passed, ready for deployment
#   1 - One or more checks failed

set -e  # Exit on error

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

# Counters
PASSED=0
FAILED=0
WARNINGS=0

# Helper functions
print_header() {
    echo ""
    echo -e "${BLUE}======================================================================${NC}"
    echo -e "${BLUE}$1${NC}"
    echo -e "${BLUE}======================================================================${NC}"
}

print_check() {
    echo -e "  Checking: $1"
}

print_pass() {
    echo -e "${GREEN}✅ PASS${NC}: $1"
    ((PASSED++))
}

print_fail() {
    echo -e "${RED}❌ FAIL${NC}: $1"
    ((FAILED++))
}

print_warn() {
    echo -e "${YELLOW}⚠️  WARN${NC}: $1"
    ((WARNINGS++))
}

print_info() {
    echo -e "${BLUE}ℹ️  INFO${NC}: $1"
}

# Get script directory (works even if called from different location)
SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
BOT_DIR="$( cd "$SCRIPT_DIR/.." && pwd )"
SLIDE_SYSTEM_DIR="$( cd "$BOT_DIR/../.." && pwd )"
REPO_ROOT="$( cd "$SLIDE_SYSTEM_DIR/../.." && pwd )"

print_header "PRE-DEPLOYMENT CHECKLIST FOR SCREENSHARE BOT"
echo "Bot Directory: $BOT_DIR"
echo "Slide System Directory: $SLIDE_SYSTEM_DIR"
echo "Repository Root: $REPO_ROOT"
echo ""

#==============================================================================
# 1. CHECK DOCKERFILE
#==============================================================================
print_header "1. DOCKERFILE VALIDATION"

DOCKERFILE="$SLIDE_SYSTEM_DIR/Dockerfile"

if [ ! -f "$DOCKERFILE" ]; then
    print_fail "Dockerfile not found at $DOCKERFILE"
else
    print_pass "Dockerfile exists at $DOCKERFILE"

    # Check for screenshare bot installation
    print_check "Screenshare bot dependencies installation"
    if grep -q "cd bots/screenshare-bot" "$DOCKERFILE" && grep -q "uv pip install" "$DOCKERFILE"; then
        print_pass "Dockerfile includes screenshare bot dependency installation"
    else
        print_fail "Dockerfile does NOT include screenshare bot installation (see DOCKERFILE-VALIDATION.md)"
    fi

    # Check for Playwright installation
    print_check "Playwright browser installation"
    if grep -q "playwright install" "$DOCKERFILE"; then
        print_pass "Dockerfile includes Playwright browser installation"
    else
        print_fail "Dockerfile does NOT include Playwright installation (see DOCKERFILE-VALIDATION.md)"
    fi

    # Check for venv creation
    print_check "Virtual environment creation"
    if grep -q "python3 -m venv .venv" "$DOCKERFILE" | grep -q "screenshare-bot"; then
        print_pass "Dockerfile creates venv for screenshare bot"
    else
        print_warn "Cannot confirm venv creation for screenshare bot in Dockerfile"
    fi
fi

#==============================================================================
# 2. CHECK ENVIRONMENT VARIABLES
#==============================================================================
print_header "2. ENVIRONMENT VARIABLES VALIDATION"

print_info "Running validate_railway_config.py..."
cd "$BOT_DIR"

# Check if venv exists
if [ ! -d ".venv" ]; then
    print_warn "Virtual environment not found at $BOT_DIR/.venv"
    print_info "Attempting to create venv and install dependencies..."

    python3 -m venv .venv
    source .venv/bin/activate
    pip install -q --upgrade pip

    # Install from pyproject.toml if it exists
    if [ -f "pyproject.toml" ]; then
        pip install -q .
    elif [ -f "requirements.txt" ]; then
        pip install -q -r requirements.txt
    else
        print_fail "No pyproject.toml or requirements.txt found"
    fi
else
    source .venv/bin/activate
fi

# Run validation script
if [ -f "scripts/validate_railway_config.py" ]; then
    if python scripts/validate_railway_config.py > /tmp/railway_validation.log 2>&1; then
        print_pass "Environment validation passed (all checks successful)"
    else
        print_fail "Environment validation failed (see /tmp/railway_validation.log for details)"
        cat /tmp/railway_validation.log
    fi
else
    print_fail "Validation script not found: scripts/validate_railway_config.py"
fi

#==============================================================================
# 3. CHECK TESTS
#==============================================================================
print_header "3. TESTS VALIDATION"

print_check "Running unit tests"
cd "$REPO_ROOT"

# Check if pnpm is available
if command -v pnpm &> /dev/null; then
    if pnpm nx test screenshare-bot --skip-nx-cache > /tmp/test_output.log 2>&1; then
        print_pass "All tests passed"
    else
        print_fail "Tests failed (see /tmp/test_output.log for details)"
        tail -20 /tmp/test_output.log
    fi
else
    print_warn "pnpm not found, skipping tests (tests should be run before deployment)"
fi

#==============================================================================
# 4. CHECK REQUIRED FILES
#==============================================================================
print_header "4. REQUIRED FILES VALIDATION"

REQUIRED_FILES=(
    "$BOT_DIR/bot.py"
    "$BOT_DIR/screenshare_bot.py"
    "$BOT_DIR/deck_url_validator.py"
    "$BOT_DIR/performance_monitor.py"
    "$BOT_DIR/requirements.txt"
    "$BOT_DIR/pyproject.toml"
    "$BOT_DIR/RAILWAY-CONFIG.md"
    "$BOT_DIR/DOCKERFILE-VALIDATION.md"
    "$BOT_DIR/scripts/validate_railway_config.py"
    "$SLIDE_SYSTEM_DIR/Dockerfile"
)

for file in "${REQUIRED_FILES[@]}"; do
    if [ -f "$file" ]; then
        print_pass "Required file exists: $(basename $file)"
    else
        print_fail "Required file missing: $file"
    fi
done

#==============================================================================
# 5. CHECK BOT MODULES
#==============================================================================
print_header "5. BOT MODULES VALIDATION"

cd "$BOT_DIR"
source .venv/bin/activate

print_check "Checking bot.py imports"
if python -c "import bot; print('OK')" > /dev/null 2>&1; then
    print_pass "bot.py can be imported"
else
    print_fail "bot.py cannot be imported (check for syntax errors)"
fi

print_check "Checking deck_url_validator imports"
if python -c "import deck_url_validator; print('OK')" > /dev/null 2>&1; then
    print_pass "deck_url_validator.py can be imported"
else
    print_fail "deck_url_validator.py cannot be imported"
fi

print_check "Checking performance_monitor imports"
if python -c "import performance_monitor; print('OK')" > /dev/null 2>&1; then
    print_pass "performance_monitor.py can be imported"
else
    print_fail "performance_monitor.py cannot be imported"
fi

#==============================================================================
# 6. CHECK DEPENDENCIES
#==============================================================================
print_header "6. PYTHON DEPENDENCIES VALIDATION"

REQUIRED_PACKAGES=(
    "pipecat"
    "daily"
    "playwright"
    "PIL"
    "aiohttp"
    "psutil"
    "dotenv"
)

for package in "${REQUIRED_PACKAGES[@]}"; do
    print_check "Checking package: $package"

    case $package in
        "pipecat")
            if python -c "import pipecat; print('OK')" > /dev/null 2>&1; then
                VERSION=$(python -c "import pipecat; print(getattr(pipecat, '__version__', 'unknown'))" 2>/dev/null)
                print_pass "pipecat is installed (version: $VERSION)"
            else
                print_fail "pipecat is NOT installed (critical for bot functionality)"
            fi
            ;;
        "daily")
            if python -c "import daily; print('OK')" > /dev/null 2>&1; then
                print_pass "daily-python is installed"
            else
                print_fail "daily-python is NOT installed"
            fi
            ;;
        "playwright")
            if python -c "import playwright; print('OK')" > /dev/null 2>&1; then
                print_pass "playwright is installed"

                # Check if browsers are installed (this may fail, which is OK locally)
                print_check "Checking Playwright browsers"
                if python -c "from playwright.sync_api import sync_playwright; p = sync_playwright().start(); p.chromium.launch(); p.stop()" > /dev/null 2>&1; then
                    print_pass "Playwright Chromium browser is installed"
                else
                    print_warn "Playwright browsers not installed locally (OK - Railway will install)"
                fi
            else
                print_fail "playwright is NOT installed"
            fi
            ;;
        "PIL")
            if python -c "from PIL import Image; print('OK')" > /dev/null 2>&1; then
                print_pass "Pillow (PIL) is installed"
            else
                print_fail "Pillow is NOT installed"
            fi
            ;;
        "aiohttp")
            if python -c "import aiohttp; print('OK')" > /dev/null 2>&1; then
                VERSION=$(python -c "import aiohttp; print(aiohttp.__version__)" 2>/dev/null)
                print_pass "aiohttp is installed (version: $VERSION)"
            else
                print_fail "aiohttp is NOT installed"
            fi
            ;;
        "psutil")
            if python -c "import psutil; print('OK')" > /dev/null 2>&1; then
                VERSION=$(python -c "import psutil; print(psutil.__version__)" 2>/dev/null)
                print_pass "psutil is installed (version: $VERSION)"
            else
                print_fail "psutil is NOT installed"
            fi
            ;;
        "dotenv")
            if python -c "import dotenv; print('OK')" > /dev/null 2>&1; then
                print_pass "python-dotenv is installed"
            else
                print_fail "python-dotenv is NOT installed"
            fi
            ;;
    esac
done

#==============================================================================
# 7. CHECK DOCUMENTATION
#==============================================================================
print_header "7. DOCUMENTATION VALIDATION"

REQUIRED_DOCS=(
    "$BOT_DIR/RAILWAY-CONFIG.md"
    "$BOT_DIR/DOCKERFILE-VALIDATION.md"
    "$BOT_DIR/RAILWAY-CONFIG-ANALYSIS.md"
)

for doc in "${REQUIRED_DOCS[@]}"; do
    if [ -f "$doc" ]; then
        # Check if file has content (not empty)
        if [ -s "$doc" ]; then
            LINES=$(wc -l < "$doc")
            print_pass "Documentation exists and has content: $(basename $doc) ($LINES lines)"
        else
            print_fail "Documentation exists but is empty: $(basename $doc)"
        fi
    else
        print_fail "Documentation missing: $(basename $doc)"
    fi
done

#==============================================================================
# 8. CHECK GIT STATUS
#==============================================================================
print_header "8. GIT STATUS CHECK"

cd "$REPO_ROOT"

# Check if there are uncommitted changes to critical files
print_check "Checking for uncommitted changes"
if git diff --quiet "$SLIDE_SYSTEM_DIR/Dockerfile"; then
    print_pass "Dockerfile has no uncommitted changes"
else
    print_warn "Dockerfile has uncommitted changes (commit before deploying)"
fi

if git diff --quiet "$BOT_DIR"; then
    print_pass "Screenshare bot directory has no uncommitted changes"
else
    print_warn "Screenshare bot directory has uncommitted changes (commit before deploying)"
fi

# Check current branch
CURRENT_BRANCH=$(git rev-parse --abbrev-ref HEAD)
print_info "Current branch: $CURRENT_BRANCH"

if [ "$CURRENT_BRANCH" = "main" ]; then
    print_warn "You are on main branch (deploy will trigger automatically)"
else
    print_pass "You are on branch: $CURRENT_BRANCH (safe for testing)"
fi

#==============================================================================
# 9. SUMMARY
#==============================================================================
print_header "SUMMARY"

echo ""
echo -e "${GREEN}✅ Checks Passed: $PASSED${NC}"
echo -e "${YELLOW}⚠️  Warnings: $WARNINGS${NC}"
echo -e "${RED}❌ Checks Failed: $FAILED${NC}"
echo ""

if [ $FAILED -eq 0 ]; then
    print_header "🎉 ALL CRITICAL CHECKS PASSED - READY FOR DEPLOYMENT"
    echo ""
    echo "Next steps:"
    echo "  1. Commit any uncommitted changes"
    echo "  2. Push to Railway: git push origin main (or your branch)"
    echo "  3. Monitor Railway build logs"
    echo "  4. Run post-deployment validation"
    echo ""
    echo "See RAILWAY-CONFIG.md for detailed deployment instructions."
    echo ""
    exit 0
else
    print_header "❌ SOME CHECKS FAILED - FIX ISSUES BEFORE DEPLOYING"
    echo ""
    echo "Please fix the failed checks above before deploying to Railway."
    echo ""
    echo "Common issues:"
    echo "  - Dockerfile missing screenshare bot installation"
    echo "  - Missing environment variables"
    echo "  - Missing Python dependencies"
    echo "  - Test failures"
    echo ""
    echo "See DOCKERFILE-VALIDATION.md and RAILWAY-CONFIG.md for help."
    echo ""
    exit 1
fi
