import { fileURLToPath as __fileURLToPath } from 'url';
import { dirname as __pathDirname } from 'path';
const __filename = __fileURLToPath(import.meta.url);
const __dirname = __pathDirname(__filename);
import { logger } from "./logger.js";
var ErrorCode = /* @__PURE__ */ ((ErrorCode2) => {
  ErrorCode2["AUTH_FAILED"] = "AUTH_FAILED";
  ErrorCode2["TOKEN_EXPIRED"] = "TOKEN_EXPIRED";
  ErrorCode2["INVALID_CREDENTIALS"] = "INVALID_CREDENTIALS";
  ErrorCode2["FILE_NOT_FOUND"] = "FILE_NOT_FOUND";
  ErrorCode2["PERMISSION_DENIED"] = "PERMISSION_DENIED";
  ErrorCode2["DISK_FULL"] = "DISK_FULL";
  ErrorCode2["NOT_GIT_REPO"] = "NOT_GIT_REPO";
  ErrorCode2["GIT_COMMAND_FAILED"] = "GIT_COMMAND_FAILED";
  ErrorCode2["INVALID_BRANCH"] = "INVALID_BRANCH";
  ErrorCode2["DB_CONNECTION_FAILED"] = "DB_CONNECTION_FAILED";
  ErrorCode2["DB_QUERY_FAILED"] = "DB_QUERY_FAILED";
  ErrorCode2["DB_CORRUPTION"] = "DB_CORRUPTION";
  ErrorCode2["NETWORK_ERROR"] = "NETWORK_ERROR";
  ErrorCode2["API_ERROR"] = "API_ERROR";
  ErrorCode2["TIMEOUT"] = "TIMEOUT";
  ErrorCode2["INVALID_INPUT"] = "INVALID_INPUT";
  ErrorCode2["VALIDATION_FAILED"] = "VALIDATION_FAILED";
  ErrorCode2["UNKNOWN_ERROR"] = "UNKNOWN_ERROR";
  ErrorCode2["OPERATION_FAILED"] = "OPERATION_FAILED";
  ErrorCode2["CONFIGURATION_ERROR"] = "CONFIGURATION_ERROR";
  return ErrorCode2;
})(ErrorCode || {});
class StackMemoryError extends Error {
  code;
  context;
  userMessage;
  recoverable;
  constructor(code, message, userMessage, context = {}, recoverable = false, cause) {
    super(message);
    this.name = "StackMemoryError";
    this.code = code;
    this.context = context;
    this.userMessage = userMessage || this.getDefaultUserMessage(code);
    this.recoverable = recoverable;
    if (cause && Error.captureStackTrace) {
      Error.captureStackTrace(this, StackMemoryError);
    }
    logger.error(message, cause, {
      code,
      context,
      recoverable,
      userMessage: this.userMessage
    });
  }
  getDefaultUserMessage(code) {
    switch (code) {
      case "AUTH_FAILED" /* AUTH_FAILED */:
        return "Authentication failed. Please check your credentials and try again.";
      case "NOT_GIT_REPO" /* NOT_GIT_REPO */:
        return "This command requires a git repository. Please run it from within a git repository.";
      case "PERMISSION_DENIED" /* PERMISSION_DENIED */:
        return "Permission denied. Please check file permissions or run with appropriate privileges.";
      case "NETWORK_ERROR" /* NETWORK_ERROR */:
        return "Network error. Please check your internet connection and try again.";
      case "INVALID_INPUT" /* INVALID_INPUT */:
        return "Invalid input provided. Please check your command and try again.";
      case "DB_CONNECTION_FAILED" /* DB_CONNECTION_FAILED */:
        return "Database connection failed. Please try again or contact support if the issue persists.";
      case "GIT_COMMAND_FAILED" /* GIT_COMMAND_FAILED */:
        return "Git operation failed. Please ensure your repository is in a valid state.";
      default:
        return "An unexpected error occurred. Please try again or contact support.";
    }
  }
  static fromNodeError(nodeError, context = {}) {
    const code = nodeError.code;
    switch (code) {
      case "ENOENT":
        return new StackMemoryError(
          "FILE_NOT_FOUND" /* FILE_NOT_FOUND */,
          `File or directory not found: ${nodeError.path}`,
          "The requested file or directory was not found.",
          { ...context, path: nodeError.path },
          false,
          nodeError
        );
      case "EACCES":
      case "EPERM":
        return new StackMemoryError(
          "PERMISSION_DENIED" /* PERMISSION_DENIED */,
          `Permission denied: ${nodeError.path}`,
          "Permission denied. Please check file permissions.",
          { ...context, path: nodeError.path },
          true,
          nodeError
        );
      case "ENOSPC":
        return new StackMemoryError(
          "DISK_FULL" /* DISK_FULL */,
          "No space left on device",
          "Insufficient disk space. Please free up space and try again.",
          context,
          true,
          nodeError
        );
      case "ETIMEDOUT":
        return new StackMemoryError(
          "TIMEOUT" /* TIMEOUT */,
          "Operation timed out",
          "The operation timed out. Please try again.",
          context,
          true,
          nodeError
        );
      default:
        return new StackMemoryError(
          "UNKNOWN_ERROR" /* UNKNOWN_ERROR */,
          nodeError.message,
          "An unexpected system error occurred.",
          { ...context, nodeErrorCode: code },
          false,
          nodeError
        );
    }
  }
}
class ErrorHandler {
  static retryMap = /* @__PURE__ */ new Map();
  static MAX_RETRIES = 3;
  static handle(error, operation) {
    if (error instanceof StackMemoryError) {
      console.error(`\u274C ${error.userMessage}`);
      if (error.recoverable) {
        console.error("\u{1F4A1} This error may be recoverable. Please try again.");
      }
      process.exit(1);
    }
    if (error instanceof Error) {
      let stackMemoryError;
      if ("code" in error && typeof error.code === "string") {
        stackMemoryError = StackMemoryError.fromNodeError(
          error,
          { operation }
        );
      } else {
        stackMemoryError = new StackMemoryError(
          "OPERATION_FAILED" /* OPERATION_FAILED */,
          `Operation '${operation}' failed: ${error.message}`,
          `Operation failed: ${error.message}`,
          { operation },
          false,
          error
        );
      }
      console.error(`\u274C ${stackMemoryError.userMessage}`);
      if (stackMemoryError.recoverable) {
        console.error("\u{1F4A1} This error may be recoverable. Please try again.");
      }
      process.exit(1);
    }
    const unknownError = new StackMemoryError(
      "UNKNOWN_ERROR" /* UNKNOWN_ERROR */,
      `Unknown error in operation '${operation}': ${String(error)}`,
      "An unexpected error occurred.",
      { operation, errorType: typeof error },
      false
    );
    console.error(`\u274C ${unknownError.userMessage}`);
    process.exit(1);
  }
  static async safeExecute(operation, operationName, fallback) {
    try {
      return await operation();
    } catch (error) {
      if (fallback !== void 0) {
        logger.warn(`Operation '${operationName}' failed, using fallback`, {
          error: String(error)
        });
        return fallback;
      }
      ErrorHandler.handle(error, operationName);
    }
  }
  static async withRetry(operation, operationName, maxRetries = ErrorHandler.MAX_RETRIES) {
    let lastError;
    for (let attempt = 1; attempt <= maxRetries; attempt++) {
      try {
        const result = await operation();
        ErrorHandler.retryMap.delete(operationName);
        return result;
      } catch (error) {
        lastError = error;
        if (error instanceof StackMemoryError && !error.recoverable) {
          ErrorHandler.handle(error, operationName);
        }
        if (attempt === maxRetries) {
          break;
        }
        const delay = Math.min(1e3 * Math.pow(2, attempt - 1), 5e3);
        logger.warn(
          `Attempt ${attempt}/${maxRetries} failed for '${operationName}', retrying in ${delay}ms`,
          {
            error: String(error)
          }
        );
        await new Promise((resolve) => setTimeout(resolve, delay));
      }
    }
    ErrorHandler.handle(
      lastError,
      `${operationName} (after ${maxRetries} attempts)`
    );
  }
  static createCircuitBreaker(operation, operationName, threshold = 5) {
    let failures = 0;
    let lastFailure = 0;
    const resetTimeout = 3e4;
    return async () => {
      const now = Date.now();
      if (now - lastFailure > resetTimeout) {
        failures = 0;
      }
      if (failures >= threshold) {
        throw new StackMemoryError(
          "OPERATION_FAILED" /* OPERATION_FAILED */,
          `Circuit breaker open for '${operationName}'`,
          `Operation temporarily unavailable. Please try again later.`,
          { operationName, failures, threshold },
          true
        );
      }
      try {
        const result = await operation();
        failures = 0;
        return result;
      } catch (error) {
        failures++;
        lastFailure = now;
        throw error;
      }
    };
  }
}
const validateInput = (value, name, validator) => {
  if (!validator(value)) {
    throw new StackMemoryError(
      "INVALID_INPUT" /* INVALID_INPUT */,
      `Invalid ${name}: ${String(value)}`,
      `Please provide a valid ${name}.`,
      { name, value },
      true
    );
  }
};
const validateEmail = (email) => {
  const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
  if (!emailRegex.test(email) || email.length > 254) {
    throw new StackMemoryError(
      "INVALID_INPUT" /* INVALID_INPUT */,
      `Invalid email format: ${email}`,
      "Please provide a valid email address.",
      { email },
      true
    );
  }
};
const validatePath = (filePath) => {
  if (!filePath || filePath.includes("..") || filePath.includes("\0")) {
    throw new StackMemoryError(
      "INVALID_INPUT" /* INVALID_INPUT */,
      `Invalid path: ${filePath}`,
      "Invalid file path provided.",
      { path: filePath },
      true
    );
  }
};
export {
  ErrorCode,
  ErrorHandler,
  StackMemoryError,
  validateEmail,
  validateInput,
  validatePath
};
//# sourceMappingURL=error-handler.js.map
