import { promises as fs } from "fs";
import path from "path";

const LOGS_DIR = path.join(process.cwd(), "logs");

export type GenerationLogLevel = "INFO" | "WARNING" | "ERROR" | "SUCCESS";

export interface GenerationLogEntry {
  timestamp: string;
  level: GenerationLogLevel;
  event: string;
  postId?: string;
  projectId?: string;
  message: string;
  details?: Record<string, unknown>;
}

async function ensureLogsDir() {
  await fs.mkdir(LOGS_DIR, { recursive: true });
}

function logFilePath(date = new Date()) {
  return path.join(LOGS_DIR, `generation-${date.toISOString().slice(0, 10)}.log`);
}

/** Append one generation event (creates daily log file if missing). */
export async function logGeneration(input: {
  level: GenerationLogLevel;
  event: string;
  postId?: string;
  projectId?: string;
  message: string;
  details?: Record<string, unknown>;
}): Promise<GenerationLogEntry> {
  await ensureLogsDir();
  const entry: GenerationLogEntry = {
    timestamp: new Date().toISOString(),
    level: input.level,
    event: input.event,
    postId: input.postId,
    projectId: input.projectId,
    message: input.message,
    details: input.details,
  };
  await fs.appendFile(logFilePath(), `${JSON.stringify(entry)}\n`, "utf-8");
  return entry;
}

/** Truncate large prompts for log readability. */
export function truncateForLog(text: string | undefined | null, max = 4000): string {
  const value = (text ?? "").trim();
  if (value.length <= max) return value;
  return `${value.slice(0, max)}…[truncated ${value.length - max} chars]`;
}
