// utils/punish.js
import { PermissionsBitField } from "discord.js";
import fs from "fs";
import path from "path";

// تحميل config.json بطريقة آمنة
const configPath = path.join(process.cwd(), "config.json");
const rawData = fs.readFileSync(configPath, "utf8");
const config = JSON.parse(rawData);

// استيراد sendLog بطريقة ESM
import { sendLog } from "../logger.js";

export async function tryStripElevatedRoles(member, client) {
  try {
    if (!member || !member.roles) return;
    if (!member.manageable) return;
    const me = member.guild.members.me;
    if (!me) return;
    const myPos = me.roles.highest.position;
    for (const role of member.roles.cache.values()) {
      if (role.managed) continue;
      if (role.id === member.guild.id) continue;
      if (role.position >= myPos) continue;
      if (
        role.permissions.has(PermissionsBitField.Flags.Administrator) ||
        role.permissions.has(PermissionsBitField.Flags.ManageGuild) ||
        role.permissions.has(PermissionsBitField.Flags.ManageRoles)
      ) {
        await member.roles.remove(role).catch(() => {});
      }
    }
  } catch (e) {
    // ignore
  }
}

export async function punish(member, client, pointsTotal) {
  const thresholds = config.thresholds || {};
  try {
    if (!member || !member.moderatable) {
      await sendLog(client, `❌ Tried to punish ${member?.user?.tag || member?.id} but not moderatable.`);
      return;
    }

    if (pointsTotal >= (thresholds.ban || 10)) {
      try {
        await member.ban({ reason: `Reached ${pointsTotal} points` });
        await sendLog(client, `🔨 Banned ${member.user.tag} (${member.id}) for reaching ${pointsTotal} points.`);
        return;
      } catch (err) {
        await sendLog(client, `❌ Error applying ban to ${member.user.tag}: ${err.message}`);
      }
    }

    if (pointsTotal >= (thresholds.timeout24h || 8)) {
      try {
        await member.timeout(24 * 60 * 60 * 1000, `Reached ${pointsTotal} points`);
        await sendLog(client, `⏰ Timed out ${member.user.tag} for 24h (points ${pointsTotal}).`);
        return;
      } catch (err) {
        await sendLog(client, `❌ Error applying 24h timeout to ${member.user.tag}: ${err.message}`);
      }
    }

    if (pointsTotal >= (thresholds.timeout2h || 5)) {
      try {
        await member.timeout(2 * 60 * 60 * 1000, `Reached ${pointsTotal} points`);
        await sendLog(client, `⏰ Timed out ${member.user.tag} for 1h (points ${pointsTotal}).`);
        return;
      } catch (err) {
        await sendLog(client, `❌ Error applying 1h timeout to ${member.user.tag}: ${err.message}`);
      }
    }
  } catch (e) {
    try {
      await sendLog(client, `❌ Error applying punishment: ${e.message}`);
    } catch (_) {}
  }
}
