#!/bin/bash
set -e

echo "Installing OpenCrates..."

# Check if Rust is installed
if ! command -v rustc &> /dev/null; then
    echo "Rust is not installed. Installing Rust..."
    curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y
    source ~/.cargo/env
fi

# Check if OpenAI API key is set
if [ -z "$OPENAI_API_KEY" ]; then
    echo "Warning: OPENAI_API_KEY environment variable is not set."
    echo "You can set it later with: export OPENAI_API_KEY=your_key_here"
fi

# Install aider if not present
if ! command -v aider &> /dev/null; then
    echo "Installing aider..."
    python -m pip install aider-chat
fi

# Install opencrates from source
echo "Installing OpenCrates from source..."
cargo install --path .

# Create default config
echo "Creating default configuration..."
mkdir -p ~/.config/opencrates
cat > ~/.config/opencrates/config.toml << 'EOF'
[server]
host = "127.0.0.1"
port = 8080
workers = 4

[database]
url = "sqlite:~/.config/opencrates/opencrates.db"
max_connections = 10

[ai]
default_model = "gpt-4"
max_tokens = 4096
temperature = 0.7

[registry]
url = "https://crates.io"
cache_ttl = 3600

[logging]
level = "info"
format = "json"
EOF

echo "OpenCrates installed successfully!"
echo ""
echo "Quick start:"
echo "  opencrates init my-project"
echo "  opencrates generate --name my-crate --description 'My awesome crate'"
echo "  opencrates serve"
echo ""
echo "For more information, run: opencrates --help" 