#!/bin/bash
# Install syntaxis-api server with configuration
#
# Usage:
#   ./scripts/install-syntaxis-api.sh [--config-dir /path/to/config] [--binary /path/to/binary]
#
# This script:
# 1. Copies the template configuration file to a user-specified location
# 2. Creates a run-syntaxis-api.sh wrapper script to start the server with the config
# 3. Shows instructions for starting the server

set -e

# Parse command line arguments
CONFIG_DIR="$HOME/.config/syntaxis-api"
BINARY=""

while [[ $# -gt 0 ]]; do
    case $1 in
        --config-dir)
            CONFIG_DIR="$2"
            shift 2
            ;;
        --binary)
            BINARY="$2"
            shift 2
            ;;
        *)
            echo "Unknown option: $1"
            exit 1
            ;;
    esac
done

# Determine binary path
if [ -z "$BINARY" ]; then
    PROJECT_ROOT="$(pwd)"
    BINARY="$PROJECT_ROOT/target/release/syntaxis-api"
fi

# Check if binary exists
if [ ! -f "$BINARY" ]; then
    echo "❌ Binary not found at: $BINARY"
    echo "Please run: cargo build -p syntaxis-api --release"
    exit 1
fi

echo "✓ Using binary: $BINARY"

# Create config directory
mkdir -p "$CONFIG_DIR"
echo "✓ Created config directory: $CONFIG_DIR"

# Get config file path
CONFIG_FILE="$CONFIG_DIR/syntaxis-api-config.toml"

# Check if config already exists
if [ -f "$CONFIG_FILE" ]; then
    echo "⚠️  Config file already exists at: $CONFIG_FILE"
    read -p "Overwrite? (y/N): " RESPONSE
    if [ "$RESPONSE" != "y" ]; then
        echo "Installation cancelled"
        exit 0
    fi
fi

# Copy template to config location
TEMPLATE="syntaxis-api-config.template.toml"
if [ ! -f "$TEMPLATE" ]; then
    echo "❌ Template not found: $TEMPLATE"
    exit 1
fi

cp "$TEMPLATE" "$CONFIG_FILE"
echo "✓ Created config file: $CONFIG_FILE"

# Create run-syntaxis-api.sh script
RUN_SCRIPT="$CONFIG_DIR/run-syntaxis-api.sh"

cat > "$RUN_SCRIPT" << 'EOF'
#!/bin/bash
# Lifecycle API Server Runner
# Generated by install-syntaxis-api.sh
#
# This script starts the syntaxis-api with the configuration file.
# Edit the configuration file to change settings:
#   nano CONFIG_FILE_PATH

exec BINARY_PATH --config CONFIG_FILE_PATH "$@"
EOF

# Replace placeholders
sed -i '' "s|BINARY_PATH|$BINARY|g" "$RUN_SCRIPT"
sed -i '' "s|CONFIG_FILE_PATH|$CONFIG_FILE|g" "$RUN_SCRIPT"
chmod +x "$RUN_SCRIPT"
echo "✓ Created run script: $RUN_SCRIPT"

# Display instructions
echo ""
echo "✅ Installation complete!"
echo ""
echo "Configuration:"
echo "  Config file: $CONFIG_FILE"
echo "  Binary: $BINARY"
echo "  Run script: $RUN_SCRIPT"
echo ""
echo "Quick Start:"
echo "  1. Edit configuration: nano $CONFIG_FILE"
echo "  2. Start server: $RUN_SCRIPT"
echo "  3. Check health: curl http://localhost:3000/api/health"
echo ""
