import discord
from discord.ext import commands
from discord.commands import Option
import traceback

# Helper function to generate the content of the message
def generate_content(data):
    """
    Generates a formatted string based on the provided data dictionary.

    Parameters:
    data (dict): A dictionary containing the entry information.

    Returns:
    str: A formatted string representing the entry.
    """
    content = (
        f"Name ID: {data['name_id']}\n"
        f"Grund: {data['grund']}\n"
        f"Datum: {data['datum']}\n"
        f"Aktion: {data['aktion']}\n"
        f"Moderator: {data['moderator']}\n"
        f"Beweis: {data['beweis']}"
    )
    return content

# Modal for editing entries
class EditModal(discord.ui.Modal):
    def init(self, original_message, data):
        self.original_message = original_message
        self.data = data
        super().init(title="Eintrag bearbeiten")

        # Define TextInput fields
        self.name_id_input = discord.ui.TextInput(
            label="Name ID",
            default=data['name_id']
        )
        self.grund_input = discord.ui.TextInput(
            label="Grund",
            default=data['grund']
        )
        self.datum_input = discord.ui.TextInput(
            label="Datum",
            default=data['datum']
        )
        self.aktion_input = discord.ui.TextInput(
            label="Aktion",
            default=data['aktion']
        )
        self.moderator_input = discord.ui.TextInput(
            label="Moderator",
            default=data['moderator']
        )
        self.beweis_input = discord.ui.TextInput(
            label="Beweis",
            default=data['beweis'],
            style=discord.TextStyle.long
        )

        # Add TextInput fields to the modal
        self.add_item(self.name_id_input)
        self.add_item(self.grund_input)
        self.add_item(self.datum_input)
        self.add_item(self.aktion_input)
        self.add_item(self.moderator_input)
        self.add_item(self.beweis_input)

    async def on_submit(self, interaction: discord.Interaction):
        # Update the data dictionary with new values from the modal
        self.data['name_id'] = self.name_id_input.value
        self.data['grund'] = self.grund_input.value
        self.data['datum'] = self.datum_input.value
        self.data['aktion'] = self.aktion_input.value
        self.data['moderator'] = self.moderator_input.value
        self.data['beweis'] = self.beweis_input.value

        # Generate new content and edit the original message
        content = generate_content(self.data)
        await self.original_message.edit(content=content)
        await interaction.response.send_message(
            "Eintrag wurde erfolgreich bearbeitet.",
            ephemeral=True
        )

# View containing the edit button
class EditView(discord.ui.View):
    def init(self, original_message, data):
        super().init(timeout=None)
        self.original_message = original_message
        self.data = data

    @discord.ui.button(label="Bearbeiten", style=discord.ButtonStyle.primary)
    async def edit_button(self, button: discord.ui.Button, interaction: discord.Interaction):
        # Open the EditModal when the button is clicked
        modal = EditModal(self.original_message, self.data)
        await interaction.response.send_modal(modal)

# The main Cog containing the slash command
class Beweis(commands.Cog):
    def init(self, bot):
        self.bot = bot  # Store the bot instance
        self.forum_channel_id = 123456789012345678  # Replace with your actual forum channel ID

    @commands.slash_command(name="eintrag", description="Erstellt einen Beweiseintrag.")
    async def beweiseintrag(
        self,
        ctx: discord.ApplicationContext,
        case_id: Option(str, "Gib die Case ID ein"),
        name_id: Option(str, "Gib die Name ID ein"),
        grund: Option(str, "Gib den Grund ein"),
        datum: Option(str, "Gib das Datum ein"),
        aktion: Option(str, "Gib die Aktion ein"),
        moderator: Option(str, "Gib den Moderator ein"),
        beweis: Option(str, "Füge den Beweis hinzu")
    ):
        """Handles the /eintrag command to create an evidence entry."""
        await ctx.defer(ephemeral=True)  # Defer the response for longer processing time
        try:
            # Fetch the forum channel
            channel = self.bot.get_channel(self.forum_channel_id)

            if channel is None:
                await ctx.respond("Der angegebene Kanal wurde nicht gefunden.", ephemeral=True)
                return
            if not isinstance(channel, discord.ForumChannel):
                await ctx.respond("Der angegebene Kanal ist kein Forumkanal.", ephemeral=True)
                return

            # Prepare data for the entry
            data = {
                'case_id': case_id,
                'name_id': name_id,
                'grund': grund,
                'datum': datum,
                'aktion': aktion,
                'moderator': moderator,
                'beweis': beweis
            }

            content = generate_content(data)
            view = EditView(None, data)

            # Create a new thread in the forum channel with the initial message
            thread = await channel.create_thread(
                name=f"Case ID: {case_id}",
                content=content,
                view=view
            )

            # Access the initial message (starter message)
            starter_message = thread.get_message(thread.id)
            if starter_message is None:
                # Fetch the starter message if not immediately available
                starter_message = await thread.fetch_message(thread.id)

            view.original_message = starter_message  # Set the original message in the view

            await ctx.respond(f"Beweiseintrag für Case ID {case_id} wurde erfolgreich erstellt.", ephemeral=True)

        except Exception as e:
            # Use e.traceback to access the traceback
            traceback_str = ''.join(traceback.format_exception(type(e), e, e.traceback))
\n{traceback_str}\n", ephemeral=True)">

# Function to set up the cog
def setup(bot):
    bot.add_cog(Beweis(bot))

Es soll mit pycord 2.6 kompatibel sein.