import os
import shutil
import subprocess
import sys
import discord
from discord.ext import commands
from discord import app_commands

class GitUpdateCog(commands.Cog):
    def __init__(self, bot: commands.Bot):
        self.bot = bot

    @app_commands.command(
        name="update", 
        description="Updates the bot code from GitLab and restarts the bot. (Admin Only)"
    )
    async def update(self, interaction: discord.Interaction):
        # Check for administrator permission
        if not interaction.user.guild_permissions.administrator:
            await interaction.response.send_message("You do not have permission to run this command.", ephemeral=True)
            return

        # Respond with an initial message
        await interaction.response.send_message("Initiating update. The bot will restart shortly...", ephemeral=True)
        
        # Define absolute paths and repository URL
        target_dir = "/home/ubuntu/wdiscordbot-internal-server-aws"
        repo_url = "https://gitlab.com/pancakes1234/wdiscordbot-internal-server-aws.git"
        restart_script = "/home/ubuntu/wdiscordbot-internal-server-aws/bot.py"
        
        try:
            if os.path.exists(target_dir):
                shutil.rmtree(target_dir)
                await interaction.followup.send(f"Removed directory: {target_dir}", ephemeral=True)
            else:
                await interaction.followup.send(f"Directory {target_dir} does not exist; proceeding with clone...", ephemeral=True)
            
            # Clone the repository
            subprocess.run(["git", "clone", repo_url, target_dir], check=True)
            await interaction.followup.send("Repository cloned successfully.", ephemeral=True)
        except Exception as e:
            error_msg = f"Update failed: {e}"
            print(error_msg)
            await interaction.followup.send(error_msg, ephemeral=True)
            return
        
        try:
            await interaction.followup.send("Bot has updated to the latest commit and is restarting...", ephemeral=True)
            # Optionally change working directory if your bot expects it:
            os.chdir(target_dir)
            # Restart the bot by replacing the current process with the new version
            os.execv(sys.executable, [sys.executable, restart_script])
        except Exception as e:
            error_msg = f"Failed to restart bot: {e}"
            print(error_msg)
            await interaction.followup.send(error_msg, ephemeral=True)

async def setup(bot: commands.Bot):
    await bot.add_cog(GitUpdateCog(bot))
