import fs from "fs";
import path from "path";
function isLoggingEnabled() {
  const value = process.env.LOG_ENABLED;
  return value === "true" || value === "1";
}
class FileLogger {
  static BASE_DIR = "logger";
  logDir;
  logFile;
  enabled;
  constructor(options) {
    const { folder, filename, enabled } = options;
    this.enabled = enabled ?? isLoggingEnabled();
    this.logDir = path.join(
      process.cwd(),
      FileLogger.BASE_DIR,
      folder || ""
    );
    this.logFile = path.join(this.logDir, `${filename}.log`);
  }
  ensureDir() {
    if (!fs.existsSync(this.logDir)) {
      try {
        fs.mkdirSync(this.logDir, { recursive: true });
      } catch (error) {
        console.error("[FileLogger] Failed to create directory:", error);
      }
    }
  }
  async write(level, action, data) {
    if (!this.enabled) return;
    this.ensureDir();
    const timestamp = (/* @__PURE__ */ new Date()).toISOString();
    const levelStr = level.toUpperCase().padEnd(5);
    const entry = [
      `[${timestamp}] [${levelStr}] [${action}]`,
      data ? JSON.stringify(data, null, 2) : "",
      "-".repeat(50),
      ""
    ].join("\n");
    try {
      await fs.promises.appendFile(this.logFile, entry);
    } catch (error) {
      console.error(`[FileLogger] Failed to write to ${this.logFile}:`, error);
    }
  }
  /** Log with debug level */
  async debug(action, data) {
    return this.write("debug", action, data);
  }
  /** Log with info level */
  async info(action, data) {
    return this.write("info", action, data);
  }
  /** Log with warn level */
  async warn(action, data) {
    return this.write("warn", action, data);
  }
  /** Log with error level */
  async error(action, data) {
    return this.write("error", action, data);
  }
  /** Alias for info() */
  async log(action, data) {
    return this.info(action, data);
  }
  /** Clear this logger's log file */
  async clear() {
    if (fs.existsSync(this.logFile)) {
      try {
        await fs.promises.unlink(this.logFile);
      } catch (error) {
        console.error(`[FileLogger] Failed to clear ${this.logFile}:`, error);
      }
    }
  }
  /** Get the full path to the log file */
  getLogPath() {
    return this.logFile;
  }
  /**
   * Clear all .log files in a folder
   * @param folder - Subfolder within logger/ (optional)
   * @returns Number of files deleted
   */
  static async clearAll(folder) {
    const dir = path.join(
      process.cwd(),
      FileLogger.BASE_DIR,
      folder || ""
    );
    if (!fs.existsSync(dir)) return 0;
    let count = 0;
    const files = await fs.promises.readdir(dir);
    for (const file of files) {
      if (file.endsWith(".log")) {
        await fs.promises.unlink(path.join(dir, file));
        count++;
      }
    }
    return count;
  }
}
export {
  FileLogger
};
