import fs from 'fs';
import path from 'path';

const logFile = path.join(process.cwd(), 'logs', 'mcp-server.log');
const logDir = path.dirname(logFile);

const ensureLogDir = () => {
  try {
    if (!fs.existsSync(logDir)) {
      fs.mkdirSync(logDir, { recursive: true });
    }
  } catch {
    // Silent fail if directory cannot be created
  }
};

function write(level: string, message: string, meta?: any) {
  const line = JSON.stringify({
    ts: new Date().toISOString(),
    level,
    message,
    ...(meta ? { meta } : {})
  });

  try {
    ensureLogDir();
    fs.appendFileSync(logFile, line + '\n', { encoding: 'utf8' });
  } catch (err) {
    // If logging to file fails, we might want to fall back to stderr 
    // but in MCP stdio mode, this could break the protocol.
  }
}

export const logger = {
  info(message: string, meta?: any) {
    write('info', message, meta);
  },
  warn(message: string, meta?: any) {
    write('warn', message, meta);
  },
  error(message: string, meta?: any) {
    write('error', message, meta);
  }
};
