import { promises as fs } from 'fs';
import path from 'path';

const dataDir = path.resolve(process.cwd(), 'data');
const dataFile = path.join(dataDir, 'alerts.json');

const DEFAULT_ALERTS = {
  enabled: false,
  pushover: {
    userKey: '',
    apiToken: ''
  },
  defaults: {
    enabled: true,
    warnPercent: 80,
    critPercent: 90,
    cooldownMinutes: 60,
    once: false,
    includePools: true
  }
};

async function ensureStore() {
  await fs.mkdir(dataDir, { recursive: true });
  try {
    await fs.access(dataFile);
  } catch {
    await fs.writeFile(dataFile, JSON.stringify(DEFAULT_ALERTS, null, 2), 'utf-8');
  }
}

const deepMerge = (base, patch) => {
  if (!patch || typeof patch !== 'object') {
    return base;
  }
  const next = { ...base };
  Object.entries(patch).forEach(([key, value]) => {
    if (value && typeof value === 'object' && !Array.isArray(value)) {
      next[key] = deepMerge(base[key] ?? {}, value);
      return;
    }
    next[key] = value;
  });
  return next;
};

export async function readAlertsConfig() {
  await ensureStore();
  const raw = await fs.readFile(dataFile, 'utf-8');
  try {
    const parsed = JSON.parse(raw);
    return deepMerge(DEFAULT_ALERTS, parsed);
  } catch {
    return { ...DEFAULT_ALERTS };
  }
}

export async function writeAlertsConfig(patch) {
  const current = await readAlertsConfig();
  const merged = deepMerge(current, patch);
  await fs.writeFile(dataFile, JSON.stringify(merged, null, 2), 'utf-8');
  return merged;
}

export { DEFAULT_ALERTS };

