/**
 * @fileoverview OrdoJS CLI - File system utilities
 */

import fs from 'fs/promises';
import path from 'path';

/**
 * Read a file from disk
 */
export async function readFile(filePath: string): Promise<string> {
  try {
    return await fs.readFile(filePath, 'utf-8');
  } catch (error) {
    if (error instanceof Error && 'code' in error && error.code === 'ENOENT') {
      throw new Error(`File not found: ${filePath}`);
    }
    throw error;
  }
}

/**
 * Write a file to disk
 */
export async function writeFile(filePath: string, content: string): Promise<void> {
  try {
    // Ensure the directory exists
    await mkdir(path.dirname(filePath), { recursive: true });

    // Write the file
    await fs.writeFile(filePath, content, 'utf-8');
  } catch (error) {
    throw new Error(`Failed to write file ${filePath}: ${error instanceof Error ? error.message : String(error)}`);
  }
}

/**
 * Create a directory
 */
export async function mkdir(dirPath: string, options?: fs.MakeDirectoryOptions): Promise<void> {
  try {
    await fs.mkdir(dirPath, options);
  } catch (error) {
    // Ignore if directory already exists
    if (error instanceof Error && 'code' in error && error.code !== 'EEXIST') {
      throw new Error(`Failed to create directory ${dirPath}: ${error instanceof Error ? error.message : String(error)}`);
    }
  }
}

/**
 * Check if a file exists
 */
export async function fileExists(filePath: string): Promise<boolean> {
  try {
    await fs.access(filePath);
    return true;
  } catch {
    return false;
  }
}

/**
 * Delete a file
 */
export async function deleteFile(filePath: string): Promise<void> {
  try {
    await fs.unlink(filePath);
  } catch (error) {
    if (error instanceof Error && 'code' in error && error.code !== 'ENOENT') {
      throw new Error(`Failed to delete file ${filePath}: ${error instanceof Error ? error.message : String(error)}`);
    }
  }
}
/**
 * Read directory contents
 */
export async function readdir(dirPath: string): Promise<string[]> {
  try {
    return await fs.readdir(dirPath);
  } catch (error) {
    throw new Error(`Failed to read directory ${dirPath}: ${error instanceof Error ? error.message : String(error)}`);
  }
}

/**
 * Get file stats
 */
export async function stat(filePath: string): Promise<fs.Stats> {
  try {
    return await fs.stat(filePath);
  } catch (error) {
    throw new Error(`Failed to get stats for ${filePath}: ${error instanceof Error ? error.message : String(error)}`);
  }
}

/**
 * Copy a file
 */
export async function copyFile(src: string, dest: string): Promise<void> {
  try {
    await fs.copyFile(src, dest);
  } catch (error) {
    throw new Error(`Failed to copy file from ${src} to ${dest}: ${error instanceof Error ? error.message : String(error)}`);
  }
}
