import log from "electron-log/main";
import fs from "fs";
import path from "path";

const findFileCaseInsensitive = async (
  extensionlessFilePath: string,
  extensions: string[],
): Promise<string | null> => {
  const directory: string = path.dirname(extensionlessFilePath);
  try {
    const matchingFiles = fs
      .readdirSync(directory)
      .filter((file: string) =>
        extensions.some((ext) =>
          file.toLowerCase().endsWith(ext.toLowerCase()),
        ),
      );
    const files: string[] = [];
    matchingFiles.forEach((file) => {
      const fullPath = path.join(directory, file);
      files.push(fullPath);
    });

    // Return the first matching file if needed
    if (files.length > 0) {
      return files[0];
    }
  } catch (error) {
    log.error(`Failed to read directory ${directory}:`, error);
    throw error;
  }

  return null;
};

export { findFileCaseInsensitive };
