'use strict';

const fs = require('fs');
const path = require('path');

class StructuredLogger {
  constructor(opts = {}) {
    this.maxEntries = opts.maxEntries || 2000;
    this.dailyDir = opts.dailyDir || 'logs';
    this.entries = [];
    this._bus = opts.bus || null;
    this._consoleEnabled = opts.console !== false;
  }

  _write(level, message) {
    const entry = {
      timestamp: new Date().toISOString(),
      time: new Date().toLocaleTimeString(),
      level,
      message,
    };
    this.entries.push(entry);
    if (this.entries.length > this.maxEntries) this.entries.shift();
    if (this._onEntry) this._onEntry(entry);
    if (this._bus) this._bus.emit('log', entry);
    if (this._consoleEnabled) {
      const sym = { info: 'ℹ', warn: '⚠', error: '✖', success: '✔' }[level] || '•';
      console.log(`[${entry.timestamp}] ${sym} ${message}`);
    }
    this._writeDaily(entry);
  }

  onEntry(fn) { this._onEntry = fn; }

  _writeDaily(entry) {
    try {
      if (!fs.existsSync(this.dailyDir)) fs.mkdirSync(this.dailyDir, { recursive: true });
      const date = entry.timestamp.slice(0, 10);
      const file = path.join(this.dailyDir, `${date}.log`);
      fs.appendFileSync(file, JSON.stringify(entry) + '\n');
    } catch (_) {}
  }

  info(msg) { this._write('info', msg); }
  warn(msg) { this._write('warn', msg); }
  error(msg) { this._write('error', msg); }
  success(msg) { this._write('success', msg); }

  clear() {
    this.entries = [];
  }

  recent(limit = 100) {
    return this.entries.slice(-limit);
  }
}

module.exports = { StructuredLogger };
