#!/bin/bash
# DSS MCP Plugin Dependency Installer
#
# Automatically discovers and installs dependencies for all plugins
# in the dss_mcp/plugins/ directory.
#
# Usage:
#   ./tools/install_plugin_deps.sh          # Install all plugin dependencies
#   ./tools/install_plugin_deps.sh --check  # Check for dependency files only

set -e

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PLUGINS_DIR="$SCRIPT_DIR/dss_mcp/plugins"
CHECK_ONLY=false

# Parse arguments
if [[ "$1" == "--check" ]]; then
    CHECK_ONLY=true
fi

echo "======================================"
echo "DSS MCP Plugin Dependency Installer"
echo "======================================"
echo ""

# Find all plugin requirements files
REQUIREMENTS_FILES=()
while IFS= read -r -d '' file; do
    REQUIREMENTS_FILES+=("$file")
done < <(find "$PLUGINS_DIR" -name "requirements.txt" -print0 2>/dev/null)

if [ ${#REQUIREMENTS_FILES[@]} -eq 0 ]; then
    echo "✓ No plugin dependencies found (no requirements.txt files)"
    exit 0
fi

echo "Found ${#REQUIREMENTS_FILES[@]} plugin(s) with dependencies:"
echo ""

for req_file in "${REQUIREMENTS_FILES[@]}"; do
    plugin_name=$(basename "$(dirname "$req_file")")
    echo "  • $plugin_name"
    echo "    └─ $req_file"
done

echo ""

if [ "$CHECK_ONLY" = true ]; then
    echo "✓ Check complete (use without --check to install)"
    exit 0
fi

# Install dependencies
echo "Installing dependencies..."
echo ""

for req_file in "${REQUIREMENTS_FILES[@]}"; do
    plugin_name=$(basename "$(dirname "$req_file")")

    echo "──────────────────────────────────────"
    echo "Installing: $plugin_name"
    echo "──────────────────────────────────────"

    # Show what will be installed
    echo "Dependencies:"
    cat "$req_file" | sed 's/^/  • /'
    echo ""

    # Install with pip
    if pip3 install -r "$req_file"; then
        echo "✓ Successfully installed dependencies for $plugin_name"
    else
        echo "✗ Failed to install dependencies for $plugin_name"
        echo "  Please check $req_file for conflicts"
        exit 1
    fi

    echo ""
done

echo "======================================"
echo "✓ All plugin dependencies installed"
echo "======================================"
echo ""
echo "Next steps:"
echo "  1. Restart DSS MCP server: supervisorctl restart dss-mcp"
echo "  2. Verify plugins loaded: Check server logs"
