#!/bin/bash
#
# Setup script for SimpleChisel MCP server
# Creates the necessary directory structure and configuration files
# for running the HAgent MCP server with SimpleChisel
#
# Optimization: Uses cached template in .cache/setup_simplechisel_mcp for faster setup

# Set default values - find hagent repo root from script location
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
HAGENT_ROOT=${HAGENT_ROOT:-$(cd "${SCRIPT_DIR}/.." && pwd)}
# Default to 2025.10 image
HAGENT_DOCKER=${HAGENT_DOCKER:-"mascucsc/hagent-simplechisel:2025.10"}

# Use current directory as base directory unless specified
BASE_DIR=${1:-$(pwd)}

# Cache directory for template (shared across all setups)
CACHE_TEMPLATE_DIR="${HAGENT_ROOT}/.cache/setup_simplechisel_mcp"

# Function to create the initial template
create_template() {
  echo "Creating cached template at ${CACHE_TEMPLATE_DIR}..."
  mkdir -p "${CACHE_TEMPLATE_DIR}"

  # Create directories in template
  mkdir -p "${CACHE_TEMPLATE_DIR}/build" "${CACHE_TEMPLATE_DIR}/cache" "${CACHE_TEMPLATE_DIR}/cache/mcp" "${CACHE_TEMPLATE_DIR}/logs"

  # Populate repo via shallow clone if not already cached
  if [[ ! -d "${CACHE_TEMPLATE_DIR}/repo/.git" ]]; then
    echo "Cloning SimpleChisel repo (shallow) into template..."
    rm -rf "${CACHE_TEMPLATE_DIR}/repo" 2>/dev/null || true
    if command -v git >/dev/null 2>&1; then
      if git clone --depth 1 https://github.com/masc-ucsc/simplechisel.git "${CACHE_TEMPLATE_DIR}/repo"; then
        echo "Clone completed."
      else
        echo "Warning: git clone failed. Falling back to minimal repo scaffold." >&2
        mkdir -p "${CACHE_TEMPLATE_DIR}/repo"
      fi
    else
      echo "Warning: git not found. Creating minimal repo scaffold instead." >&2
      mkdir -p "${CACHE_TEMPLATE_DIR}/repo"
    fi
  else
    echo "Using existing cached repo at ${CACHE_TEMPLATE_DIR}/repo"
  fi

  echo "Template created successfully"
}

# Check if template exists, create if not
if [[ ! -d "${CACHE_TEMPLATE_DIR}" ]]; then
  create_template
else
  echo "Using cached template at ${CACHE_TEMPLATE_DIR}"
fi

# Copy template to target directory (fast operation)
# Resolve absolute paths to avoid copying to self
BASE_DIR_ABS=$(cd "${BASE_DIR}" && pwd)
CACHE_TEMPLATE_DIR_ABS=$(dirname "${CACHE_TEMPLATE_DIR}")

if [[ "${BASE_DIR_ABS}" != "${CACHE_TEMPLATE_DIR_ABS}" ]]; then
  echo "Copying template to ${BASE_DIR}..."
  cp -a "${CACHE_TEMPLATE_DIR}/repo" "${BASE_DIR}/" 2>/dev/null || mkdir -p "${BASE_DIR}/repo"
  cp -a "${CACHE_TEMPLATE_DIR}/build" "${BASE_DIR}/" 2>/dev/null || mkdir -p "${BASE_DIR}/build"
  cp -a "${CACHE_TEMPLATE_DIR}/cache" "${BASE_DIR}/" 2>/dev/null || mkdir -p "${BASE_DIR}/cache"
  cp -a "${CACHE_TEMPLATE_DIR}/logs" "${BASE_DIR}/" 2>/dev/null || mkdir -p "${BASE_DIR}/logs"
  # Ensure mcp directory exists
  mkdir -p "${BASE_DIR}/cache/mcp"
else
  echo "Skipping copy - target directory is same as cache parent directory"
fi

# Path to the MCP server
MCP_SERVER_PATH="${HAGENT_ROOT}/hagent/mcp/hagent-mcp-server.py"

# Create the hagent_server.sh script
cat >"${BASE_DIR}/hagent_server.sh" <<EOF
#!/bin/bash
#
# HAgent MCP Server launcher
# Generated by setup_simplechisel_mcp.sh
#
# Usage: ./hagent_server.sh [--debug]
# Use --debug for detailed logging and raw I/O transaction logs in cache/mcp/

export HAGENT_ROOT="${HAGENT_ROOT}"
export HAGENT_DOCKER="${HAGENT_DOCKER}"
export HAGENT_EXECUTION_MODE="docker"
export HAGENT_REPO_DIR="${BASE_DIR}/repo"
export HAGENT_BUILD_DIR="${BASE_DIR}/build"
export HAGENT_CACHE_DIR="${BASE_DIR}/cache"
export HAGENT_OUTPUT_DIR="${BASE_DIR}/logs"

# Pass through any command line arguments (like --debug)
uv run python ${MCP_SERVER_PATH} "\$@"
EOF

# Make the script executable
chmod +x "${BASE_DIR}/hagent_server.sh"

echo
echo "Setup complete!"
echo
echo "Directory structure created:"
echo "- ${BASE_DIR}/repo  (for source code)"
echo "- ${BASE_DIR}/build (for build outputs)"
echo "- ${BASE_DIR}/cache (for cached files)"
echo "- ${BASE_DIR}/cache/mcp (for MCP transaction logs)"
echo
echo "Generated files:"
echo "- ${BASE_DIR}/hagent_server.sh (executable server launcher)"
echo
echo "To use with Gemini:"
echo "  gemini add hagent ${BASE_DIR}/hagent_server.sh"
echo
echo "To test manually:"
echo "  ${BASE_DIR}/hagent_server.sh"
echo
