import { shell } from 'electron';
import { existsSync } from 'fs';
import { homedir } from 'os';
import { join } from 'path';
import log from 'electron-log';

/**
 * Expand tilde (~) in path to home directory
 */
function expandTilde(filePath: string): string {
  if (filePath.startsWith('~/') || filePath === '~') {
    return join(homedir(), filePath.slice(2));
  }
  return filePath;
}

/**
 * Open a file or folder in Finder and select it
 * @param path - Absolute path to the file or folder (tilde paths like ~/.gemrc are supported)
 * @returns true if successful, false otherwise
 */
export async function showInFinder(path: string): Promise<boolean> {
  try {
    // Expand tilde to home directory
    const expandedPath = expandTilde(path);

    if (!existsSync(expandedPath)) {
      log.error(`Cannot show in Finder - path does not exist: ${expandedPath}`);
      return false;
    }

    // showItemInFolder reveals the file in Finder (returns void)
    shell.showItemInFolder(expandedPath);
    log.info(`Opened in Finder: ${expandedPath}`);
    return true;
  } catch (error) {
    log.error('Error opening in Finder:', error);
    return false;
  }
}

/**
 * Open a path in the default application
 * @param path - Absolute path to the file or folder (tilde paths like ~/.gemrc are supported)
 * @returns true if successful, false otherwise
 */
export async function openPath(path: string): Promise<boolean> {
  try {
    // Expand tilde to home directory
    const expandedPath = expandTilde(path);

    if (!existsSync(expandedPath)) {
      log.error(`Cannot open - path does not exist: ${expandedPath}`);
      return false;
    }

    // openPath opens the file/folder with the default application
    const result = await shell.openPath(expandedPath);

    if (result === '') {
      log.info(`Opened path: ${expandedPath}`);
      return true;
    } else {
      log.error(`Failed to open path: ${expandedPath} - ${result}`);
      return false;
    }
  } catch (error) {
    log.error('Error opening path:', error);
    return false;
  }
}
