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

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

export type LlmRequestAuditEntry = {
  kind: "tool" | "skill";
  sessionId: string;
  clientSessionId: string;
  traceId?: string;
  projectId?: string;
  target: string;
  reason: string;
  reasonProvided: boolean;
  payload?: Record<string, unknown>;
};

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

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

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