#!/bin/bash

# Playwright Setup Script for Stock Bot
# This script specifically handles Playwright installation and browser setup

set -e

# Colors
GREEN='\033[0;32m'
BLUE='\033[0;34m'
RED='\033[0;31m'
NC='\033[0m'

log_info() {
    echo -e "${BLUE}[INFO]${NC} $1"
}

log_success() {
    echo -e "${GREEN}[SUCCESS]${NC} $1"
}

log_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

# Check if we're in the project directory
check_project_directory() {
    if [[ ! -f "package.json" ]]; then
        log_error "Please run this script from the project root directory"
        exit 1
    fi
}

# Install Playwright dependencies
install_playwright_deps() {
    log_info "Installing Playwright system dependencies..."
    bunx playwright install-deps chromium
    log_success "Playwright system dependencies installed"
}

# Install Playwright browsers
install_browsers() {
    log_info "Installing Playwright browsers..."
    
    # Install all browsers
    bunx playwright install chromium
    bunx playwright install firefox
    bunx playwright install webkit
    
    log_success "All Playwright browsers installed"
}

# Test Playwright installation
test_playwright() {
    log_info "Testing Playwright installation..."
    
    # Create a simple test script
    cat > /tmp/test-playwright.js << 'EOF'
const { chromium } = require('playwright');

(async () => {
  try {
    const browser = await chromium.launch({ headless: true });
    const page = await browser.newPage();
    await page.goto('https://example.com');
    const title = await page.title();
    console.log('✅ Playwright test successful! Page title:', title);
    await browser.close();
  } catch (error) {
    console.error('❌ Playwright test failed:', error.message);
    process.exit(1);
  }
})();
EOF
    
    # Run the test
    node /tmp/test-playwright.js
    
    # Clean up
    rm /tmp/test-playwright.js
    
    log_success "Playwright test completed successfully"
}

# Main function
main() {
    log_info "Setting up Playwright for Stock Bot..."
    
    check_project_directory
    install_playwright_deps
    install_browsers
    test_playwright
    
    log_success "Playwright setup completed!"
    log_info "You can now run your browser automation scripts"
}

# Show help
show_help() {
    echo "Playwright Setup Script for Stock Bot"
    echo ""
    echo "Usage: $0 [OPTIONS]"
    echo ""
    echo "Options:"
    echo "  -h, --help     Show this help message"
    echo "  --test-only    Only run the Playwright test"
    echo "  --deps-only    Only install system dependencies"
    echo ""
}

# Parse arguments
case "${1:-}" in
    -h|--help)
        show_help
        exit 0
        ;;
    --test-only)
        check_project_directory
        test_playwright
        exit 0
        ;;
    --deps-only)
        install_playwright_deps
        exit 0
        ;;
    "")
        main
        ;;
    *)
        log_error "Unknown option: $1"
        show_help
        exit 1
        ;;
esac
