#!/usr/bin/env bash
# Start extension registry service

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_DIR="$(dirname "$SCRIPT_DIR")"

# Default values
CONFIG_FILE="${PROJECT_DIR}/config.toml"
PORT=8082
LOG_LEVEL="info"
JSON_LOG=false

# Parse arguments
while [[ $# -gt 0 ]]; do
    case $1 in
        --config)
            CONFIG_FILE="$2"
            shift 2
            ;;
        --port)
            PORT="$2"
            shift 2
            ;;
        --log-level)
            LOG_LEVEL="$2"
            shift 2
            ;;
        --json-log)
            JSON_LOG=true
            shift
            ;;
        --help)
            echo "Usage: $0 [OPTIONS]"
            echo ""
            echo "Options:"
            echo "  --config FILE      Configuration file (default: config.toml)"
            echo "  --port PORT        Port to listen on (default: 8082)"
            echo "  --log-level LEVEL  Log level (trace|debug|info|warn|error)"
            echo "  --json-log         Enable JSON logging"
            echo "  --help             Show this help"
            exit 0
            ;;
        *)
            echo "Unknown option: $1"
            echo "Use --help for usage information"
            exit 1
            ;;
    esac
done

# Check if config file exists
if [[ ! -f "$CONFIG_FILE" ]]; then
    echo "Error: Configuration file not found: $CONFIG_FILE"
    echo "Create config.toml from config.example.toml"
    exit 1
fi

# Build if needed
if [[ ! -f "${PROJECT_DIR}/target/release/extension-registry" ]]; then
    echo "Building extension-registry..."
    cd "$PROJECT_DIR"
    cargo build --release
fi

# Start service
echo "Starting extension-registry service..."
echo "  Config: $CONFIG_FILE"
echo "  Port: $PORT"
echo "  Log level: $LOG_LEVEL"

cd "$PROJECT_DIR"

ARGS=(
    --config "$CONFIG_FILE"
    --port "$PORT"
    --log-level "$LOG_LEVEL"
)

if [[ "$JSON_LOG" == "true" ]]; then
    ARGS+=(--json-log)
fi

exec ./target/release/extension-registry "${ARGS[@]}"
