import fs from "fs";
import path from "path";
import { fileURLToPath } from "url";

const __dirname = path.dirname(fileURLToPath(import.meta.url));
const STATS_FILE = path.join(__dirname, "../.stats.json");

let data = null;

function load() {
  if (data) return data;
  try {
    data = JSON.parse(fs.readFileSync(STATS_FILE, "utf8"));
  } catch {
    data = {};
  }
  return data;
}

function save() {
  fs.writeFileSync(STATS_FILE, JSON.stringify(data, null, 2));
}

export function record(category, key) {
  load();
  if (!data[category]) data[category] = {};
  data[category][key] = (data[category][key] || 0) + 1;
  save();
}

export function sortByUsage(category, items, getKey = v => v) {
  load();
  const counts = data[category] || {};
  return [...items].sort((a, b) => (counts[getKey(b)] || 0) - (counts[getKey(a)] || 0));
}
