import { mkdirSync, appendFileSync, existsSync } from "fs";
import { join } from "path";

type LogLevel = "INFO" | "WARN" | "ERROR" | "DEBUG";

let logDir = "./logs";

export function initLogger(dir: string) {
  logDir = dir;
  if (!existsSync(logDir)) {
    mkdirSync(logDir, { recursive: true });
  }
}

function formatLog(level: LogLevel, component: string, message: string, data?: any): string {
  const ts = new Date().toISOString();
  const base = `[${ts}] [${level}] [${component}] ${message}`;
  return data ? `${base} ${JSON.stringify(data)}` : base;
}

function log(level: LogLevel, component: string, message: string, data?: any) {
  const line = formatLog(level, component, message, data);
  console.log(line);
  
  try {
    const logFile = join(logDir, `pi-worker-${new Date().toISOString().split("T")[0]}.log`);
    appendFileSync(logFile, line + "\n");
  } catch {}
}

export const logger = {
  info: (component: string, message: string, data?: any) => log("INFO", component, message, data),
  warn: (component: string, message: string, data?: any) => log("WARN", component, message, data),
  error: (component: string, message: string, data?: any) => log("ERROR", component, message, data),
  debug: (component: string, message: string, data?: any) => log("DEBUG", component, message, data),
};
