const fs = require("fs");
const path = require("path");
const { db } = require("./db");
const { getPlugins } = require("./plugins");

function readJsonSafe(filePath) {
  try {
    const raw = fs.readFileSync(filePath, "utf8");
    return JSON.parse(raw);
  } catch {
    return null;
  }
}

function loadStatProviders() {
  const providers = [];
  const plugins = getPlugins().filter((plugin) => plugin.enabled);
  for (const plugin of plugins) {
    const manifestPath = path.join(plugin.path, "stats.json");
    if (!fs.existsSync(manifestPath)) {
      continue;
    }
    const manifest = readJsonSafe(manifestPath);
    if (!manifest) {
      continue;
    }
    const providerPath = path.join(
      plugin.path,
      manifest.provider || "stats.js"
    );
    if (!fs.existsSync(providerPath)) {
      continue;
    }
    let provider = null;
    try {
      provider = require(providerPath);
    } catch (error) {
      console.error("Failed to load plugin stats provider", error);
      continue;
    }
    providers.push({ plugin, manifest, provider });
  }
  return providers;
}

function buildProfileSection({ plugin, manifest, provider, userId }) {
  if (!manifest.profile || typeof provider.getProfileStats !== "function") {
    return null;
  }
  let result = null;
  try {
    result = provider.getProfileStats({ db, userId, plugin, manifest });
  } catch (error) {
    console.error("Failed to load plugin profile stats", error);
    return null;
  }
  const stats = Array.isArray(result?.stats) ? result.stats : [];
  return {
    id: manifest.pluginId || plugin.id,
    title: manifest.profile.title || manifest.pluginName || plugin.name,
    emptyMessage:
      manifest.profile.emptyMessage || "No stats available yet.",
    stats
  };
}

function buildLeaderboardSection({ plugin, manifest, provider, limit }) {
  if (!manifest.leaderboards || typeof provider.getLeaderboards !== "function") {
    return null;
  }
  let result = null;
  try {
    result = provider.getLeaderboards({ db, limit, plugin, manifest });
  } catch (error) {
    console.error("Failed to load plugin leaderboards", error);
    return null;
  }
  const boards = Array.isArray(result?.boards) ? result.boards : [];
  return {
    id: manifest.pluginId || plugin.id,
    title:
      manifest.leaderboards.title || manifest.pluginName || plugin.name,
    emptyMessage:
      manifest.leaderboards.emptyMessage || "No data available yet.",
    boards
  };
}

function getPluginProfileStats(userId) {
  if (!userId) {
    return [];
  }
  return loadStatProviders()
    .map((entry) => buildProfileSection({ ...entry, userId }))
    .filter(Boolean);
}

function getPluginLeaderboards(limit = 10) {
  return loadStatProviders()
    .map((entry) => buildLeaderboardSection({ ...entry, limit }))
    .filter(Boolean);
}

module.exports = {
  getPluginProfileStats,
  getPluginLeaderboards
};
