import log from 'electron-log/main.js';
import electron from 'electron';
const { app } = electron;
import { join } from 'node:path';
import { createHash } from 'node:crypto';

let initialized = false;

export function initLogger(): void {
  if (initialized) return;
  const logDir = join(app.getPath('userData'), 'Inkling', 'logs');
  log.transports.file.resolvePathFn = () =>
    join(logDir, `main-${new Date().toISOString().slice(0, 10)}.log`);
  log.transports.file.maxSize = 5 * 1024 * 1024;
  log.transports.file.level = 'info';
  log.transports.console.level = process.env.INKLING_DEBUG === '1' ? 'debug' : 'info';
  initialized = true;
}

export function hashPrefix(text: string): string {
  return createHash('sha256').update(text).digest('hex').slice(0, 8);
}

export const logger = {
  info: (msg: string, meta?: Record<string, unknown>) => log.info(msg, meta ?? {}),
  warn: (msg: string, meta?: Record<string, unknown>) => log.warn(msg, meta ?? {}),
  error: (msg: string, meta?: Record<string, unknown>) => log.error(msg, meta ?? {}),
  debug: (msg: string, meta?: Record<string, unknown>) => log.debug(msg, meta ?? {})
};
