# write_mcp_jupyter_config
# -------------------------
# Genera o actualiza .mcp.json con la configuracion de jupyter-mcp-server.
# Usa el python del venv local con -m jupyter_mcp_server.server.
# Configura via env vars (SERVER_URL, TOKEN) — no CLI args.
# Hace merge si ya existe .mcp.json (requiere jq).
#
# USO (sourced):
#   source write_mcp_jupyter_config.sh
#   write_mcp_jupyter_config /path/to/project 8888

write_mcp_jupyter_config() {
    local project_dir="${1:-.}"
    local port="${2:-8888}"
    local mcp_file="${project_dir}/.mcp.json"
    local abs_project
    abs_project="$(cd "$project_dir" && pwd)"

    local python_bin="${abs_project}/.venv/bin/python"
    if [ ! -f "$python_bin" ]; then
        echo "write_mcp_jupyter_config: python no encontrado en ${python_bin}" >&2
        return 1
    fi

    # Verificar que el modulo esta instalado
    if ! "$python_bin" -c "import jupyter_mcp_server" 2>/dev/null; then
        echo "write_mcp_jupyter_config: jupyter_mcp_server no instalado en el venv" >&2
        return 1
    fi

    local new_config
    new_config=$(cat << EOF
{
  "mcpServers": {
    "jupyter": {
      "command": "${python_bin}",
      "args": ["-m", "jupyter_mcp_server.server"],
      "env": {
        "SERVER_URL": "http://localhost:${port}",
        "TOKEN": ""
      }
    }
  }
}
EOF
)

    if [ -f "$mcp_file" ] && command -v jq &>/dev/null; then
        # Merge conservando otros servidores MCP
        jq -s '.[0] * {mcpServers: ((.[0].mcpServers // {}) * (.[1].mcpServers // {}))}' \
            "$mcp_file" <(echo "$new_config") > "${mcp_file}.tmp"
        mv "${mcp_file}.tmp" "$mcp_file"
    else
        echo "$new_config" > "$mcp_file"
    fi

    echo "$mcp_file"
}
