import type { JsonValue } from "../../shared/src/index";
import { createHourlyJsonlWriter, logRetentionBytesForService } from "../../shared/src/rotating-jsonl";
import type { LoggerFn } from "./types";

export function createLogger(service: string, logFile: string): { logger: LoggerFn; recentLogs: unknown[] } {
  const recentLogs: unknown[] = [];
  const writer = createHourlyJsonlWriter({
    baseLogFile: logFile,
    service,
    maxBytes: logRetentionBytesForService(service),
  });
  writer.prune();
  const logger: LoggerFn = (level, message, data?: JsonValue): void => {
    const entry = data === undefined
      ? { ts: new Date().toISOString(), service, level, message }
      : { ts: new Date().toISOString(), service, level, message, data };
    recentLogs.push(entry);
    while (recentLogs.length > 500) recentLogs.shift();
    const line = `${JSON.stringify(entry)}\n`;
    try {
      writer.appendLine(line, new Date(entry.ts));
    } catch (error) {
      console.error(JSON.stringify({ ts: new Date().toISOString(), service, level: "error", message: "log_write_failed", data: String(error) }));
    }
    const consoleMethod = level === "error" ? console.error : level === "warn" ? console.warn : console.log;
    consoleMethod(line.trimEnd());
  };
  return { logger, recentLogs };
}
