#!/usr/bin/env python3
"""
LuaFind Discord bot - script protection panel bot.

Setup:
  1. pip install -U discord.py
  2. Set environment variables:
       LUAFIND_BOT_TOKEN  your bot token from the Discord developer portal
       LUAFIND_API_KEY    the bot API key from the LuaFind Bots tab
       LUAFIND_SITE       (optional) defaults to https://luafind.pages.dev
  3. python bot.py

When the bot joins a server it creates a locked #panel channel and a
"LuaFind Panel" role. Anyone with that role (or server admins) can use
the commands. Every website account has its own API key, so this bot
only ever sees that account's scripts and keys.
"""
import os
import time
import aiohttp
import discord
from discord import app_commands
from discord.ext import commands

BOT_TOKEN = os.environ["LUAFIND_BOT_TOKEN"]
API_KEY = os.environ["LUAFIND_API_KEY"]
SITE = os.environ.get("LUAFIND_SITE", "https://luafind.pages.dev").rstrip("/")
ROLE_NAME = "LuaFind Panel"
CHANNEL_NAME = "panel"
PANEL_COLOR = 0x7C3AED

DURATIONS = {"30m": "30 minutes", "1h": "1 hour", "6h": "6 hours", "1d": "1 day",
             "7d": "7 days", "30d": "30 days", "life": "Lifetime"}

intents = discord.Intents.default()
bot = commands.Bot(command_prefix="!", intents=intents)
tree = bot.tree
_started = time.time()
_scripts_cache = []


async def api(path, method="GET", data=None):
    headers = {"X-API-Key": API_KEY}
    async with aiohttp.ClientSession() as s:
        if method == "GET":
            async with s.get(SITE + path, headers=headers, timeout=aiohttp.ClientTimeout(total=20)) as r:
                return r.status, await r.json(content_type=None)
        async with s.post(SITE + path, headers=headers, json=data or {}, timeout=aiohttp.ClientTimeout(total=20)) as r:
            return r.status, await r.json(content_type=None)


async def refresh_scripts():
    global _scripts_cache
    try:
        code, data = await api("/api/bot/scripts")
        _scripts_cache = data.get("scripts", []) if code == 200 else []
    except Exception:
        _scripts_cache = []


def key_status(k, now):
    if k.get("taken"):
        return "shut down"
    exp = k.get("expires_at") or 0
    if exp and exp < now:
        return "expired"
    return "active"


async def panel_role(guild) -> discord.Role:
    for r in guild.roles:
        if r.name == ROLE_NAME and r.managed is False:
            return r
    return await guild.create_role(name=ROLE_NAME, color=PANEL_COLOR,
                                   reason="LuaFind panel role")


async def invited_by(guild) -> str:
    try:
        async for e in guild.audit_logs(limit=10, action=discord.AuditLogAction.bot_add):
            if e.target.id == guild.me.id:
                return str(e.user)
    except Exception:
        pass
    return str(guild.owner)


class RedeemModal(discord.ui.Modal, title="Redeem your key"):
    key = discord.ui.TextInput(label="Your key", placeholder="lf_...", max_length=40)

    async def on_submit(self, itx: discord.Interaction):
        code, data = await api("/api/bot/redeem?key=" + str(self.key).strip())
        if code != 200:
            await itx.response.send_message("❌ " + data.get("error", "redeem failed"), ephemeral=True)
            return
        await itx.response.send_message(
            embed=discord.Embed(title="Key valid", description=f"Script: **{data['script_name']}**\n\nRun this:\n```lua\n{data['loader']}\n```",
                                color=PANEL_COLOR),
            ephemeral=True)


class GetScriptModal(discord.ui.Modal, title="Get script"):
    key = discord.ui.TextInput(label="Your key", placeholder="lf_...", max_length=40)

    async def on_submit(self, itx: discord.Interaction):
        code, data = await api("/api/bot/redeem?key=" + str(self.key).strip())
        if code != 200:
            await itx.response.send_message("❌ " + data.get("error", "redeem failed"), ephemeral=True)
            return
        fname = data["script_name"].replace("/", "_") + ".lua"
        f = discord.File(fp=__import__("io").BytesIO(data["source"].encode()), filename=fname)
        await itx.response.send_message(
            embed=discord.Embed(title="Your protected script", description=f"**{data['script_name']}**\nRun with:\n```lua\n{data['loader']}\n```", color=PANEL_COLOR),
            file=f, ephemeral=True)


class PanelView(discord.ui.View):
    def __init__(self):
        super().__init__(timeout=None)

    @discord.ui.button(label="Redeem", style=discord.ButtonStyle.primary, custom_id="luafind:redeem")
    async def redeem(self, itx: discord.Interaction, _b: discord.ui.Button):
        await itx.response.send_modal(RedeemModal())

    @discord.ui.button(label="Get Script", style=discord.ButtonStyle.secondary, custom_id="luafind:getscript")
    async def getscript(self, itx: discord.Interaction, _b: discord.ui.Button):
        await itx.response.send_modal(GetScriptModal())

    @discord.ui.button(label="Get Stats", style=discord.ButtonStyle.secondary, custom_id="luafind:stats")
    async def stats(self, itx: discord.Interaction, _b: discord.ui.Button):
        code, data = await api(f"/api/bot/stats?discord_id={itx.user.id}")
        if code != 200:
            await itx.response.send_message("❌ stats failed", ephemeral=True)
            return
        lines = [f"**{name}** - {p['execs']} execs across {p['keys']} keys" for name, p in
                 [(x["name"], x) for x in data.get("per_script", [])]]
        e = discord.Embed(title="Your stats",
                          description=(f"Keys: **{data['keys']}**\nExecutions: **{data['execs']}**"
                                       + ("\n\n" + "\n".join(lines) if lines else "")),
                          color=PANEL_COLOR)
        await itx.response.send_message(embed=e, ephemeral=True)


bot.add_view(PanelView())


@bot.event
async def on_ready():
    await refresh_scripts()
    try:
        await tree.sync()
    except Exception as e:
        print("command sync failed:", e)
    print(f"LuaFind bot online as {bot.user} | site {SITE}")


@bot.event
async def on_guild_join(guild: discord.Guild):
    try:
        inviter = await invited_by(guild)
        role = await panel_role(guild)
        overwrites = {
            guild.default_role: discord.PermissionOverwrite(view_channel=True, send_messages=False),
            role: discord.PermissionOverwrite(view_channel=True, send_messages=True),
            guild.me: discord.PermissionOverwrite(view_channel=True, send_messages=True),
        }
        ch = discord.utils.get(guild.text_channels, name=CHANNEL_NAME)
        if ch is None:
            ch = await guild.create_text_channel(CHANNEL_NAME, overwrites=overwrites,
                                                 reason="LuaFind panel")
        e = discord.Embed(title="LuaFind Panel", color=PANEL_COLOR,
                          description=f"Script protection panel. Invited by **{inviter}**.\n\n"
                                      f"Press **Redeem** to turn your key into a loader, **Get Script** to receive the "
                                      f"protected file, or **Get Stats** for your executions.")
        e.add_field(name="Commands", value="/genkey - make a key\n/hwid reset - reset a key's device lock\n"
                                           "/amount - your key count and execs\n/uptime - bot uptime\n"
                                           "/takekey - shut a key down\n/ping - latency", inline=False)
        await ch.send(embed=e, view=PanelView())
    except Exception as e:
        print("panel setup failed in", guild.name, ":", e)


def panel_member(itx: discord.Interaction) -> bool:
    if itx.user.guild_permissions.administrator:
        return True
    role = discord.utils.get(itx.user.roles, name=ROLE_NAME)
    return role is not None


async def my_keys(itx, only_active=False):
    code, data = await api(f"/api/bot/keys?discord_id={itx.user.id}")
    if code != 200:
        return []
    keys = data.get("keys", [])
    if only_active:
        now = data.get("now", int(time.time()))
        keys = [k for k in keys if key_status(k, now) == "active"]
    return keys


@tree.command(name="genkey", description="Generate a key for a script")
@app_commands.describe(script="Which script", duration="How long the key lasts")
@app_commands.choices(duration=[app_commands.Choice(name=v, value=k) for k, v in DURATIONS.items()])
async def genkey(itx: discord.Interaction, script: str, duration: app_commands.Choice[str]):
    if not panel_member(itx):
        return await itx.response.send_message("You need the " + ROLE_NAME + " role to use LuaFind commands.", ephemeral=True)
    code, data = await api("/api/bot/genkey", "POST", {
        "script": script, "duration": duration.value,
        "discord_id": str(itx.user.id), "discord_name": str(itx.user)})
    if code != 200:
        return await itx.response.send_message("❌ " + data.get("error", "failed") +
                                               (("\nScripts: " + data["scripts"]) if "scripts" in data else ""), ephemeral=True)
    await refresh_scripts()
    e = discord.Embed(title="Key generated", description=f"Script: **{data['script']}**\nExpires: **{DURATIONS[duration.value]}**\n\n"
                                                         f"```lua\nscript_key=\"{data['key']}\";\nloadstring(game:HttpGet(\"{SITE}/loader.lua?script=YOUR_SCRIPT_ID\"))()\n```\n"
                                                         f"Your key: `{data['key']}`", color=PANEL_COLOR)
    await itx.response.send_message(embed=e, ephemeral=True)


@genkey.autocomplete("script")
async def genkey_ac(itx: discord.Interaction, current: str):
    await refresh_scripts()
    return [app_commands.Choice(name=f"{s['name']} ({s['id']})", value=s["id"])
            for s in _scripts_cache if current.lower() in s["name"].lower()][:25]


@tree.command(name="hwid", description="Reset a key's device lock")
@app_commands.describe(key="The key (optional: defaults to your most recent active key)", amount="Set extra HWID resets")
async def hwid(itx: discord.Interaction, key: str = None, amount: app_commands.Range[int, 1, 99] = None):
    if not panel_member(itx):
        return await itx.response.send_message("You need the " + ROLE_NAME + " role to use LuaFind commands.", ephemeral=True)
    if not key:
        keys = await my_keys(itx, only_active=True)
        if not keys:
            return await itx.response.send_message("You have no active keys. Pass a key with this command.", ephemeral=True)
        key = keys[0]["id"]
    code, data = await api("/api/bot/hwidreset", "POST", {"key": key, "amount": amount})
    if code != 200:
        return await itx.response.send_message("❌ " + data.get("error", "failed"), ephemeral=True)
    left = data.get("hwid_resets", "?")
    note = data.get("note", "")
    await itx.response.send_message(
        f"✅ HWID reset for `{key}`. The next device that runs it becomes the bound device. Resets left: **{left}**"
        + (f"\n({note})" if note else ""), ephemeral=True)


@tree.command(name="amount", description="How many keys you hold and your executions")
async def amount(itx: discord.Interaction):
    keys = await my_keys(itx)
    now = int(time.time())
    active = sum(1 for k in keys if key_status(k, now) == "active")
    execs = sum(k.get("exec_count", 0) for k in keys)
    await itx.response.send_message(f"You hold **{len(keys)}** keys ({active} active) with **{execs}** total executions.", ephemeral=True)


@tree.command(name="uptime", description="How long the bot has been up")
async def uptime(itx: discord.Interaction):
    s = int(time.time() - _started)
    d, s = divmod(s, 86400)
    h, s = divmod(s, 3600)
    m, _ = divmod(s, 60)
    await itx.response.send_message(f"Up for **{d}d {h}h {m}m**", ephemeral=True)


@tree.command(name="takekey", description="Shut a key down permanently")
@app_commands.describe(key="The key to shut down")
async def takekey(itx: discord.Interaction, key: str):
    if not panel_member(itx):
        return await itx.response.send_message("You need the " + ROLE_NAME + " role to use LuaFind commands.", ephemeral=True)
    code, data = await api("/api/bot/takekey", "POST", {"key": key})
    if code != 200:
        return await itx.response.send_message("❌ " + data.get("error", "failed"), ephemeral=True)
    await itx.response.send_message(f"🛑 Shut down `{data['key']}`"
                                    + (f" (was {data['discord_name']}'s key)" if data.get("discord_name") else ""), ephemeral=True)


@tree.command(name="ping", description="Bot latency")
async def ping(itx: discord.Interaction):
    await itx.response.send_message(f"Pong! **{round(bot.latency * 1000)} ms**", ephemeral=True)


if __name__ == "__main__":
    bot.run(BOT_TOKEN)
