import { appendFile, mkdir } from "node:fs/promises";
import { dirname } from "node:path";

import { config } from "../config.js";

export type LearningAuditEntry = {
  action: string;
  detail?: string;
  outcome: "accepted" | "error" | "rejected" | "skipped";
  projectId?: string;
  proposal?: Record<string, unknown>;
  sessionId: string;
  traceId?: string;
};

let logDirectoryReadyPromise: Promise<void> | null = null;

const ensureLogDirectory = async () => {
  if (!logDirectoryReadyPromise) {
    logDirectoryReadyPromise = mkdir(dirname(config.LEARNING_AUDIT_LOG_PATH), {
      recursive: true,
    }).then(() => undefined);
  }
  await logDirectoryReadyPromise;
};

export const writeLearningAuditLog = async (entry: LearningAuditEntry) => {
  await ensureLogDirectory();
  const line = JSON.stringify({
    timestamp: new Date().toISOString(),
    ...entry,
  });
  await appendFile(config.LEARNING_AUDIT_LOG_PATH, `${line}\n`, "utf8");
};
