$files = \Drupal::entityTypeManager()->getStorage('file')->loadByProperties([
  'filemime' => 'audio/wav',
]);

$file_system = \Drupal::service('file_system');
$private_scheme = 'private://';
$public_scheme = 'public://';

$count = 0;

foreach ($files as $file) {
  $original_uri = $file->getFileUri();

  if (strpos($original_uri, $public_scheme) !== 0) {
    // Already private or not in public:// — skip it
    continue;
  }

  $relative_path = str_replace($public_scheme, '', $original_uri);
  $destination_uri = $private_scheme . $relative_path;

  // Create the private directory if it doesn't exist
  $dir = dirname($destination_uri);
  $file_system->prepareDirectory($dir, FILE_CREATE_DIRECTORY);

  try {
    // Move the file physically
    $moved = $file_system->move($original_uri, $destination_uri, FILE_EXISTS_RENAME);

    if ($moved) {
      // Update file entity with new URI
      $file->setFileUri($destination_uri);
      $file->save();
      $count++;
      echo "Moved: $relative_path\n";
    }
  }
  catch (\Exception $e) {
    echo "Failed to move: $relative_path — " . $e->getMessage() . "\n";
  }
}

echo "\nDone. Moved $count file(s).\n";

