# mod_perms.py
import re
import discord
from discord.ext import commands
from modules.common.settings import cfg  # ENV-first config helper

def _parse_ids(raw: str):
    ids = []
    if not raw:
        return ids
    for tok in re.split(r'[,\s]+', raw.strip()):
        if not tok:
            continue
        try:
            ids.append(int(tok))
        except Exception:
            pass
    return ids

def get_mod_role_ids(bot: commands.Bot):
    # Read from ENV/INI via helper; allow comma-separated lists in any field
    reader = cfg(bot)
    keys = ["admin_role_id", "field_mod_role_id", "intel_mod_role_id", "moderator_role_id"]
    collected = []
    for k in keys:
        collected.extend(_parse_ids(reader.get(k, "")))
    # dedupe while preserving order
    seen = set()
    unique = []
    for i in collected:
        if i not in seen:
            seen.add(i)
            unique.append(i)
    return unique

def is_moderator_member(member: discord.Member, bot: commands.Bot) -> bool:
    if not isinstance(member, discord.Member):
        return False
    if member.guild_permissions.administrator:
        return True
    mod_ids = set(get_mod_role_ids(bot))
    return any(r.id in mod_ids for r in member.roles)

def is_moderator_userid(guild: discord.Guild, user_id: int, bot: commands.Bot) -> bool:
    m = guild.get_member(user_id)
    return is_moderator_member(m, bot) if m else False

async def require_mod_ctx(ctx: commands.Context, msg="You don’t have permission to use this."):
    if not is_moderator_member(ctx.author, ctx.bot):
        await ctx.reply(msg)
        return False
    return True

async def require_mod_interaction(interaction: discord.Interaction, msg="This command is restricted to moderators."):
    user = interaction.user
    if isinstance(user, discord.Member) and is_moderator_member(user, interaction.client):
        return True
    # Only send a response if we haven’t already
    if not interaction.response.is_done():
        await interaction.response.send_message(msg, ephemeral=True)
    else:
        await interaction.followup.send(msg, ephemeral=True)
    return False
