#!/bin/bash

# Rustelo Development Installer
# Simple setup script for development environment

set -e

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

# Project settings
PROJECT_NAME="my-rustelo-app"
TEMPLATE_DIR="$(pwd)/template"

# Functions
log() {
    echo -e "${GREEN}[INFO]${NC} $1"
}

log_warn() {
    echo -e "${YELLOW}[WARN]${NC} $1"
}

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

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

print_success() {
    echo -e "${GREEN}✓${NC} $1"
}

# Check if command exists
command_exists() {
    command -v "$1" >/dev/null 2>&1
}

# Check system requirements
check_requirements() {
    log "Checking system requirements..."

    local missing=()

    if ! command_exists git; then
        missing+=("git")
    fi

    if ! command_exists rustc; then
        missing+=("rust (install from https://rustup.rs/)")
    fi

    if ! command_exists node; then
        missing+=("node.js (install from https://nodejs.org/)")
    fi

    if ! command_exists cargo-leptos; then
        log_warn "cargo-leptos not found, will install it"
    fi

    if [ ${#missing[@]} -gt 0 ]; then
        log_error "Missing required dependencies: ${missing[*]}"
        exit 1
    fi

    print_success "System requirements check passed"
}

# Install Rust tools
install_rust_tools() {
    log "Installing Rust tools..."

    if ! command_exists cargo-leptos; then
        log "Installing cargo-leptos..."
        cargo install cargo-leptos
    fi

    print_success "Rust tools installed"
}

# Create new project
create_project() {
    # Get project name from user
    echo -n "Enter project name [$PROJECT_NAME]: "
    read -r input
    if [ -n "$input" ]; then
        PROJECT_NAME="$input"
    fi

    # Check if directory exists
    if [ -d "$PROJECT_NAME" ]; then
        log_error "Directory '$PROJECT_NAME' already exists!"
        echo -n "Remove existing directory? (y/N): "
        read -r confirm
        if [[ "$confirm" =~ ^[Yy]$ ]]; then
            rm -rf "$PROJECT_NAME"
        else
            exit 1
        fi
    fi

    log "Creating project: $PROJECT_NAME"

    # Copy template
    cp -r "$TEMPLATE_DIR" "$PROJECT_NAME"
    cd "$PROJECT_NAME"

    # Update project name in Cargo.toml
    if [ -f "Cargo.toml" ]; then
        sed -i.bak "s/name = \"rustelo\"/name = \"$PROJECT_NAME\"/" Cargo.toml
        rm -f Cargo.toml.bak
    fi

    print_success "Project created: $PROJECT_NAME"
}

# Setup environment
setup_environment() {
    log "Setting up development environment..."

    # Create .env file
    if [ ! -f ".env" ]; then
        cat > ".env" << EOF
# Development Environment Configuration
ENVIRONMENT=dev

# Server Configuration
SERVER_HOST=127.0.0.1
SERVER_PORT=3030
SERVER_PROTOCOL=http

# Database Configuration
DATABASE_URL=postgresql://dev:dev@localhost:5432/${PROJECT_NAME}_dev

# Session Configuration
SESSION_SECRET=dev-secret-not-for-production

# Features
ENABLE_AUTH=true
ENABLE_CONTENT_DB=true
ENABLE_TLS=false

# Logging
LOG_LEVEL=debug
RUST_LOG=debug
EOF
        log "Created .env file"
    fi

    # Create necessary directories
    mkdir -p public uploads logs cache config data

    print_success "Environment configured"
}

# Install dependencies
install_dependencies() {
    log "Installing dependencies..."

    # Install Rust dependencies
    log "Fetching Rust dependencies..."
    cargo fetch

    # Install Node.js dependencies
    if [ -f "package.json" ]; then
        log "Installing Node.js dependencies..."
        if command_exists pnpm; then
            pnpm install
        else
            npm install
        fi
    fi

    print_success "Dependencies installed"
}

# Build project
build_project() {
    log "Building project..."

    # Build CSS
    if [ -f "package.json" ]; then
        log "Building CSS..."
        if command_exists pnpm; then
            pnpm run build:css
        else
            npm run build:css
        fi
    fi

    # Build Rust project
    log "Building Rust code..."
    cargo build

    print_success "Project built successfully"
}

# Setup development scripts
setup_scripts() {
    log "Creating development scripts..."

    # Create start script
    cat > "start.sh" << EOF
#!/bin/bash
# Start development server
cd "\$(dirname "\$0")"
cargo leptos watch
EOF
    chmod +x "start.sh"

    # Create build script
    cat > "build.sh" << EOF
#!/bin/bash
# Build for production
cd "\$(dirname "\$0")"
cargo leptos build --release
EOF
    chmod +x "build.sh"

    print_success "Development scripts created"
}

# Display final instructions
show_instructions() {
    echo
    print_header "╭─────────────────────────────────────────────────────────╮"
    print_header "│              DEVELOPMENT SETUP COMPLETE                │"
    print_header "╰─────────────────────────────────────────────────────────╯"
    echo

    print_success "Project '$PROJECT_NAME' is ready for development!"
    echo
    echo "Next steps:"
    echo "1. cd $PROJECT_NAME"
    echo "2. ./start.sh (or: cargo leptos watch)"
    echo "3. Open http://127.0.0.1:3030 in your browser"
    echo
    echo "Available commands:"
    echo "  ./start.sh          - Start development server"
    echo "  ./build.sh          - Build for production"
    echo "  cargo leptos watch  - Start with hot reload"
    echo "  cargo build         - Build Rust code only"
    echo "  npm run dev         - Watch CSS changes"
    echo
    echo "Configuration:"
    echo "  .env                - Environment variables"
    echo "  Cargo.toml          - Rust dependencies"
    echo "  package.json        - Node.js dependencies"
    echo
    print_success "Happy coding! 🚀"
}

# Main installation
main() {
    print_header "Rustelo Development Setup"
    echo

    # Check if we're in the right directory
    if [ ! -d "$TEMPLATE_DIR" ]; then
        log_error "Template directory not found: $TEMPLATE_DIR"
        log_error "Please run this script from the Rustelo project root"
        exit 1
    fi

    # Run setup steps
    check_requirements
    install_rust_tools
    create_project
    setup_environment
    install_dependencies
    build_project
    setup_scripts

    # Show final instructions
    show_instructions
}

# Run main function
main "$@"
