'use strict';

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

const ACTIVITY_PATH = path.join(__dirname, '..', 'data', 'activity.json');
const MAX_ACTIVITY = 500;

function read() {
  try { return JSON.parse(fs.readFileSync(ACTIVITY_PATH, 'utf8')); }
  catch { return []; }
}

function write(entries) {
  fs.writeFileSync(ACTIVITY_PATH, JSON.stringify(entries, null, 2));
}

function log(level, category, message, meta = {}) {
  const entry = {
    id: Date.now().toString(36) + Math.random().toString(36).slice(2, 5),
    level,       // info | success | warning | error
    category,    // deploy | iis | file | system
    message,
    meta,
    timestamp: new Date().toISOString(),
  };

  const entries = read();
  entries.unshift(entry);
  if (entries.length > MAX_ACTIVITY) entries.splice(MAX_ACTIVITY);
  write(entries);

  // Broadcast to WebSocket clients
  if (global.broadcastLog) global.broadcastLog(message, level);
  if (global.broadcastEvent) global.broadcastEvent('activity', entry);

  return entry;
}

const info    = (cat, msg, meta) => log('info', cat, msg, meta);
const success = (cat, msg, meta) => log('success', cat, msg, meta);
const warning = (cat, msg, meta) => log('warning', cat, msg, meta);
const error   = (cat, msg, meta) => log('error', cat, msg, meta);

function getAll(limit = 100) {
  return read().slice(0, limit);
}

function clear() {
  write([]);
}

module.exports = { info, success, warning, error, getAll, clear };
