import fs from 'node:fs';
import path from 'node:path';

export class Logger {
  private logFile: string;

  constructor(logDir: string) {
    fs.mkdirSync(logDir, { recursive: true });
    this.logFile = path.join(logDir, 'watchdog.log');
  }

  private write(level: string, message: string, data?: unknown): void {
    const timestamp = new Date().toISOString();
    const entry = {
      timestamp,
      level,
      message,
      ...(data !== undefined ? { data } : {}),
    };
    const line = JSON.stringify(entry);
    console.log(`[${timestamp}] [${level.toUpperCase()}] ${message}${data ? ' ' + JSON.stringify(data) : ''}`);
    fs.appendFileSync(this.logFile, line + '\n');
  }

  info(message: string, data?: unknown): void {
    this.write('info', message, data);
  }

  warn(message: string, data?: unknown): void {
    this.write('warn', message, data);
  }

  error(message: string, data?: unknown): void {
    this.write('error', message, data);
  }
}
