from typing import List
from enum import Enum

class BLOCKS_EVENT__PROVIDER(Enum):
    GITHUB = "github"
    SLACK = "slack"
    WEBHOOK = "webhook"
    LINEAR = "linear"
    CLAUDE = "claude"
    CODEX = "codex"
    GITLAB = "gitlab"

class BLOCKS_EVENT__GITHUB__TYPE(Enum):
    ISSUE = "issue"
    PULL_REQUEST = "pull_request"
    PULL_REQUEST_REVIEW_COMMENT = "pull_request_review_comment"

class BLOCKS_EVENT__SLACK__TYPE(Enum):
    MENTION = "mention"

class BLOCKS_EVENT__LINEAR__TYPE(Enum):
    ISSUE = "issue"

class BLOCKS_EVENT__GITLAB__TYPE(Enum):
    ISSUE = "issue"
    MERGE_REQUEST = "merge_request"

class BLOCKS_EVENT__TRIGGER_ALIAS(Enum):
    SLACK_MENTION = "slack.mention"
    GITHUB_ISSUE_COMMENT = "github.issue_comment"
    GITHUB_PULL_REQUEST_COMMENT = "github.pull_request_comment"
    GITHUB_PULL_REQUEST_REVIEW_COMMENT = "github.pull_request_review_comment"
    WEBHOOK = "webhook"
    LINEAR_ISSUE_COMMENT = "linear.issue_comment"
    LINEAR_ASSIGN = "linear.assign"
    GITLAB_ISSUE_COMMENT = "gitlab.issue_comment"
    GITLAB_MERGE_REQUEST_COMMENT = "gitlab.merge_request_comment"

def get_trigger_provider_from_trigger_alias(trigger_alias: str) -> str:
    trigger_provider = BLOCKS_EVENT__PROVIDER.WEBHOOK.value
    try:
        trigger_provider = trigger_alias.split(".")[0]
    except Exception as e:
        trigger_provider = BLOCKS_EVENT__PROVIDER.WEBHOOK.value

    return trigger_provider


def format_event_context(event_type: str, event_data: dict, agent: str) -> str:

    latest_user_message = None
    formatted_context = None

    # Extract external user IDs from the event data
    # These identify the external user (GitHub, Slack, Linear, GitLab) who invoked the action
    github_external_user_id = event_data.get("$blocks.external_user_id.github", "")
    slack_external_user_id = event_data.get("$blocks.external_user_id.slack", "")
    linear_external_user_id = event_data.get("$blocks.external_user_id.linear", "")
    gitlab_external_user_id = event_data.get("$blocks.external_user_id.gitlab", "")

    # Extract user timezone from the event data
    user_timezone = event_data.get("$blocks.user.timezone", "")

    # Build timezone context info
    timezone_context = ""
    if user_timezone:
        timezone_context = f"""
    <user_timezone>
        <timezone>{user_timezone}</timezone>
        <note>When providing date/time information to the user, always check the environment's current system time (available in your &lt;env&gt; context as "Today's date") and account for this timezone. Convert times appropriately to ensure accuracy for the user's location.</note>
    </user_timezone>"""

    # Build default Linear team context
    import os
    default_team_id = os.getenv("DEFAULT_LINEAR_TEAM_ID", "")
    default_team_context = ""
    if default_team_id:
        default_team_context = f"""
    <default_linear_team>
        <note>A default Linear team has been configured for this workspace. Use this team ID when creating new Linear issues UNLESS the user explicitly specifies a different team in their request.</note>
        <team_id>{default_team_id}</team_id>
    </default_linear_team>"""

    # Build external user context info
    external_user_context = ""
    has_external_user_info = bool(github_external_user_id or slack_external_user_id or linear_external_user_id or gitlab_external_user_id)

    # Build the tool_create_github_pr reminder only for non-claude agents
    tool_create_github_pr_reminder = ""
    if agent != 'claude':
        tool_create_github_pr_reminder = "- IMPORTANT: Always use {{ tool_create_github_pr }} to create a pull request never use `gh` to create a pull request.\n"

    SYSTEM_REMINDERS = f"""<system_reminders>
{tool_create_github_pr_reminder}- IMPORTANT: Always attempt to use {{{{ tool_clone_repository_into_folder }}}} to clone a repository.
- IMPORTANT: When creating a new Linear issue/ticket, if there is a defined `linear_user_id` in the `<invoking_user_identifiers>` section of the formatted context, you should add that user ID as a subscriber to the ticket when you create it. Use the Linear MCP tools available to you to add subscribers by passing the `subscriberIds` parameter when creating the issue.
- IMPORTANT: When creating a new Linear issue/ticket, if you see a `<default_linear_team>` section in the formatted context AND the user has not explicitly specified which team to use, you MUST use the default team ID when creating the issue. If the user explicitly mentions a team name or key in their request, use their specified team instead of the default.
- IMPORTANT: Always use {{{{ tool_register_running_server_port }}}} to register a running server port for frontend apps, make sure to run the server as a background process so it persists indefinitely using `nohup bash -c 'COMMAND' > /tmp/PORT_HERE.log 2>&1 &`
</system_reminders>"""

    if has_external_user_info:
        external_user_context = f"""
    <invoking_user_identifiers>
        <note>The invoking user is identified across your connected tools. Use these identifiers to understand who triggered the action. When the user says "me", "I", or "my" in queries (e.g., "what PRs are assigned to me", "my issues"), refer to these user IDs to query the appropriate resources.</note>
        {f"<github_user_id>{github_external_user_id}</github_user_id>" if github_external_user_id else "<github_user_id>Not linked</github_user_id>"}
        {f"<slack_user_id>{slack_external_user_id}</slack_user_id>" if slack_external_user_id else "<slack_user_id>Not linked</slack_user_id>"}
        {f"<linear_user_id>{linear_external_user_id}</linear_user_id>" if linear_external_user_id else "<linear_user_id>Not linked</linear_user_id>"}
        {f"<gitlab_user_id>{gitlab_external_user_id}</gitlab_user_id>" if gitlab_external_user_id else "<gitlab_user_id>Not linked</gitlab_user_id>"}
    </invoking_user_identifiers>"""
    else:
        external_user_context = """
    <invoking_user_identifiers>
        <note>Unable to determine who is invoking this action. The user may not be linked across your connected tools. IMPORTANT: When user IDs are "Unknown", you CANNOT resolve queries about "me", "I", or "my" (e.g., "what PRs are assigned to me", "my issues", "my PRs"). You MUST inform the user that you cannot determine their identity and ask them to specify the user explicitly (e.g., by username or user ID) or link their accounts.</note>
        <github_user_id>Unknown</github_user_id>
        <slack_user_id>Unknown</slack_user_id>
        <linear_user_id>Unknown</linear_user_id>
        <gitlab_user_id>Unknown</gitlab_user_id>
    </invoking_user_identifiers>"""

    if event_type == BLOCKS_EVENT__TRIGGER_ALIAS.GITHUB_PULL_REQUEST_COMMENT.value:

        owner = event_data.get("owner", {})
        repo_name = event_data.get("repo", {})
        ref = event_data.get("ref", {})

        pull_request = event_data.get("pull_request", {})
        pull_request_title = pull_request.get("title")
        pull_request_number = pull_request.get("number")

        latest_comment = event_data.get("new_comment", {})
        latest_comment_body = latest_comment.get("body")
        latest_user_message = latest_comment_body
        latest_comment_id = latest_comment.get("id")

        # Check if there's a parent comment (thread context)
        parent_comment = event_data.get("parent_comment", {})
        parent_comment_context = ""
        if parent_comment:
            parent_comment_body = parent_comment.get("body", "")
            parent_comment_author = parent_comment.get("author", "")
            parent_comment_id = parent_comment.get("id", "")
            parent_comment_context = f"""
    <parent_comment>
        <note>This comment is part of a threaded discussion. Below is the root comment that started this thread, which may provide important context.</note>
        <parent_comment_id>{parent_comment_id}</parent_comment_id>
        <parent_comment_author>{parent_comment_author}</parent_comment_author>
        <parent_comment_body>{parent_comment_body}</parent_comment_body>
    </parent_comment>"""

        formatted_context = f"""
<formatted_context>
    <event_type>I have mentioned you in Github Pull Request #{pull_request_number} for the {owner}/{repo_name} repository. Ensure you are working on the correct branch.</event_type>
    <latest_user_message>{{latest_user_message}}</latest_user_message>
    <pull_request>
        <pull_request_number>{pull_request_number}</pull_request_number>
        <pull_request_title>{pull_request_title}</pull_request_title>
        <pull_request_ref>{ref}</pull_request_ref>
        <pull_request_comment>My latest message is within pull request comment ID: {latest_comment_id}</pull_request_comment>
    </pull_request>{parent_comment_context}{external_user_context}{timezone_context}{default_team_context}
    <important_notes>
        - The main focus is to be my latest comment, if I mention anything about "here" or "this" "pull request" I am referring to "this" github pull request #{pull_request_number} in the repo {owner}/{repo_name}. 
        - Do not update pull request title or description unless explicitly asked to do so by me.
        - Ensure you also read the pull request description and comments to understand the context of the conversation.
        - IMPORTANT: If you are asked to review the pull request, use the MCP tool `{{{{ tool_create_github_pr_review_comment_on_lines }}}}` to leave line-by-line comments on the different files in the pull request.
        - Only use line-by-line comment tools on files that are part of this PR's diff (from the PR files list) and have a patch; otherwise, post a top-level PR comment instead.
        - When creating review comments, use the PR head commit SHA for `commit_id`, and line numbers from the PR diff blob.
    </important_notes>
    <communication_guidelines_and_system_constraints>
    - You should avoid asking me follow up questions, unless absolutely necessary.
    - You should make particular note what the intended deliverable is (If I'm asking for a PR you should create a PR at the end of the task).
    > IMPORTANT: You don't need to use any tools to comment on this pull request for me to see your messages.
    However if I ask you to explicitly post a comment or update a comment you should use the appropriate tools if available.
    </communication_guidelines_and_system_constraints>
</formatted_context>

{SYSTEM_REMINDERS}
"""

    elif event_type == BLOCKS_EVENT__TRIGGER_ALIAS.GITHUB_PULL_REQUEST_REVIEW_COMMENT.value:
        owner = event_data.get("owner", {})
        repo_name = event_data.get("repo", {})
        ref = event_data.get("ref", {})

        pull_request = event_data.get("pull_request", {})
        pull_request_number = pull_request.get("number")
        latest_comment = event_data.get("new_comment", {})
        latest_comment_file_path = latest_comment.get("filename")
        latest_comment_line = latest_comment.get("line")
        latest_comment_start_line = latest_comment.get("start_line")
        latest_comment_body = latest_comment.get("body")
        latest_comment_id = latest_comment.get("id")
        latest_comment_created_at = latest_comment.get("created_at")
        latest_commend_node_id = latest_comment.get("node_id")
        latest_comment_diff_hunk = latest_comment.get("diff_hunk", "")
        in_reply_to_id = latest_comment.get("in_reply_to_id")

        # Build line reference string (range or single line)
        if latest_comment_start_line and latest_comment_start_line != latest_comment_line:
            line_ref = f"lines {latest_comment_start_line}-{latest_comment_line}"
        else:
            line_ref = f"line {latest_comment_line}"

        # Truncate diff hunk if too large
        if len(latest_comment_diff_hunk) > 3000:
            latest_comment_diff_hunk = latest_comment_diff_hunk[:3000] + "\n [... truncated diff hunk ...] To view the remainder, read the file directly."

        latest_user_message = latest_comment_body

        # Build parent comment info if this is a threaded reply
        parent_comment_info = ""
        if in_reply_to_id:
            # Check if there's a parent_comment object with full details
            parent_comment = event_data.get("parent_comment", {})
            if parent_comment:
                parent_comment_body = parent_comment.get("body", "")
                parent_comment_author = parent_comment.get("author", "")
                parent_comment_id = parent_comment.get("id", in_reply_to_id)
                parent_comment_info = f"""
    <parent_comment>
        <note>This comment is part of a threaded discussion. Below is the root comment that started this thread, which may provide important context.</note>
        <parent_comment_id>{parent_comment_id}</parent_comment_id>
        <parent_comment_author>{parent_comment_author}</parent_comment_author>
        <parent_comment_body>{parent_comment_body}</parent_comment_body>
    </parent_comment>
"""
            else:
                # Fallback if parent_comment data is not available
                parent_comment_info = f"""
    <parent_comment>
        <parent_comment_id>Parent Comment ID: {in_reply_to_id}</parent_comment_id>
        <context>This comment is part of a threaded discussion and is continuing the conversation from the parent comment.</context>
    </parent_comment>
"""

        formatted_context = f"""
<formatted_context>
    <event_type>I have mentioned you in a Github pull request review thread for the pull request #{pull_request_number} for the {owner}/{repo_name} @ {ref} branch. Ensure you are working on the correct branch.</event_type>
    <latest_user_message>{{latest_user_message}}</latest_user_message>
    <pull_request>
        <pull_request_number>{pull_request_number}</pull_request_number>
        <owner>{owner}</owner>
        <repo_name>{repo_name}</repo_name>
        <pull_request_ref>{ref}</pull_request_ref>
    </pull_request>{external_user_context}{timezone_context}
    <pull_request_review_comment>
        <latest_comment_id>My latest message is within pull request review comment ID: {latest_comment_id}</latest_comment_id>
        <latest_comment_created_at>Pull Request Review Comment Created At: {latest_comment_created_at}</latest_comment_created_at>
        <latest_commend_node_id>Pull Request Review Comment Node ID: {latest_commend_node_id}</latest_commend_node_id>{parent_comment_info}
    </pull_request_review_comment>{f'''
    <referenced_code_context>
        <referenced_filename>{latest_comment_file_path}</referenced_filename>
        <referenced_lines>{line_ref}</referenced_lines>
        <referenced_diff_hunk>{latest_comment_diff_hunk}</referenced_diff_hunk>
    </referenced_code_context>''' if latest_comment_diff_hunk else ''}
    <important_notes>
        - The main focus is to be my latest comment, if I mention anything about "here" or "this" I am referring to "this" {line_ref} in the file {latest_comment_file_path} for comment_id {latest_comment_id}. If the line is the start of a function, I am referring to the entire function, etc.
        - If I mention "pull request" I am referring to "this" github pull request #{pull_request_number} in the repo {owner}/{repo_name}.
        - Do not update pull request title or description unless explicitly asked to do so by me.
        - Ensure you also read the pull request description and comments to understand the context of the conversation.
        - Only use line-by-line comment tools on files that are part of this PR's diff (from the PR files list) and have a patch; otherwise, post a top-level PR comment instead.
        - When creating review comments, use the PR head commit SHA for `commit_id`, and line numbers from the PR diff blob.
    </important_notes>
    <communication_guidelines_and_system_constraints>
    - You should avoid asking me follow up questions, unless absolutely necessary.
    - You should make particular note what the intended deliverable is (If I'm asking for a PR you should create a PR at the end of the task).
    > IMPORTANT: You don't need to use any tools to comment on this pull request for me to see your messages.
    However if I ask you to explicitly post a comment or update a comment you should use the appropriate tools if available.
    </communication_guidelines_and_system_constraints>
</formatted_context>

{SYSTEM_REMINDERS}
"""

    elif event_type == BLOCKS_EVENT__TRIGGER_ALIAS.GITHUB_ISSUE_COMMENT.value:

        issue = event_data.get("issue", {})
        issue_title = issue.get("title")
        issue_number = issue.get("number")
        owner = event_data.get("owner")
        repo = event_data.get("repo")

        latest_comment = event_data.get("new_comment", {})
        latest_comment_body = latest_comment.get("body")
        latest_user_message = latest_comment_body
        latest_comment_id = latest_comment.get("id")
        
        formatted_context = f"""
<formatted_context>
    <event_type>I have mentioned you in a Github issue #{issue_number} for the {owner}/{repo} repository</event_type>
    <latest_user_message>{{latest_user_message}}</latest_user_message>
    <github_issue>
        <issue_number>{issue_number}</issue_number>
        <issue_title>{issue_title}</issue_title>
        <owner>{owner}</owner>
        <repo>{repo}</repo>
        <github_comment_id>My latest message is within github issue comment ID: {latest_comment_id}</github_comment_id>
    </github_issue>{external_user_context}{timezone_context}{default_team_context}
    <important_notes>
        - The main focus is to be my latest comment, if I mention anything about this "issue" I am referring to "this" github issue #{issue_number} in the repo {owner}/{repo}. 
        - Do not update issue title or description unless explicitly asked to do so by me.
        - Ensure you also read the issue description and comments to understand the context of the conversation.
    </important_notes>
    <communication_guidelines_and_system_constraints>
    - You should avoid asking me follow up questions, unless absolutely necessary.
    - You should make particular note what the intended deliverable is (If I'm asking for a PR you should create a PR at the end of the task).
    > IMPORTANT: You don't need to use any tools to comment on this issue for me to see your messages.
    However if I ask you to explicitly post a comment or update a comment you should use the appropriate tools if available.
    </communication_guidelines_and_system_constraints>
</formatted_context>

{SYSTEM_REMINDERS}
"""

    elif event_type == BLOCKS_EVENT__TRIGGER_ALIAS.SLACK_MENTION.value:

        event = event_data.get("event", {})
        text = event.get("text", "")
        channel = event.get("channel", "")
        ts = event.get("ts", "")

        latest_user_message = text

        # Check if there's a parent comment (thread context)
        parent_comment = event_data.get("parent_comment", {})
        parent_comment_context = ""
        if parent_comment:
            parent_comment_text = parent_comment.get("text", "")
            parent_comment_user = parent_comment.get("user", "")
            parent_comment_ts = parent_comment.get("ts", "")
            parent_comment_context = f"""
    <parent_comment>
        <note>This message is part of a threaded discussion. Below is the root message that started this thread, which may provide important context.</note>
        <parent_comment_ts>{parent_comment_ts}</parent_comment_ts>
        <parent_comment_user>{parent_comment_user}</parent_comment_user>
        <parent_comment_text>{parent_comment_text}</parent_comment_text>
    </parent_comment>"""

        formatted_context = f"""
<formatted_context>
    <event_type>I have mentioned you in a Slack channel or DM</event_type>
    <latest_user_message>{{latest_user_message}}</latest_user_message>
    <slack_channel>{channel}</slack_channel>
    <slack_thread_ts>{ts}</slack_thread_ts>{parent_comment_context}{external_user_context}{timezone_context}{default_team_context}
    <important_notes>
        The main focus is to be my latest message. If I mention anything about "here" I am likely referring to the Slack thread and alternatively the channel. If my message indicates that I am referring to information on the thread you should read the thread to understand the context of the conversation.
    </important_notes>
    <communication_guidelines_and_system_constraints>
        - You can respond in standard Markdown, assume I can see it properly.
        - You should avoid asking me follow up questions, unless absolutely necessary.
        - You should make particular note what the intended deliverable is (If I'm asking for a PR you should create a PR at the end of the task).
        > IMPORTANT: I can already see your messages on Slack, so you don't need to use any tools to send Slack messages for me to see them unless I explicitly ask you to post a message or reply to a thread.
    </communication_guidelines_and_system_constraints>
</formatted_context>

{SYSTEM_REMINDERS}
"""

    elif event_type == BLOCKS_EVENT__TRIGGER_ALIAS.LINEAR_ISSUE_COMMENT.value:

        issue = event_data.get("issue", {})
        issue_title = issue.get("title")
        issue_identifier = issue.get("identifier")
        issue_number = issue.get("number")
        team = issue.get("team", {})
        team_name = team.get("name", "Unknown Team")

        latest_comment = event_data.get("new_comment", {})
        latest_comment_body = latest_comment.get("body")
        latest_user_message = latest_comment_body

        # Build Linear issue context
        linear_issue_context = f"""
    <issue_identifier>{issue_identifier}</issue_identifier>
    <issue_number>{issue_number}</issue_number>
    <issue_title>{issue_title}</issue_title>
    <team_name>{team_name}</team_name>"""

        # Check if there's a parent comment (thread context)
        parent_comment = event_data.get("parent_comment", {})
        parent_comment_context = ""
        if parent_comment:
            parent_comment_body = parent_comment.get("body", "")
            parent_comment_user = parent_comment.get("user", {})
            parent_comment_user_name = parent_comment_user.get("name", "")
            parent_comment_id = parent_comment.get("id", "")
            parent_comment_context = f"""
    <parent_comment>
        <note>This comment is part of a threaded discussion. Below is the root comment that started this thread, which may provide important context.</note>
        <parent_comment_id>{parent_comment_id}</parent_comment_id>
        <parent_comment_author>{parent_comment_user_name}</parent_comment_author>
        <parent_comment_body>{parent_comment_body}</parent_comment_body>
    </parent_comment>"""

        formatted_context = f"""
<formatted_context>
    <event_type>I have mentioned you in a Linear issue {issue_identifier} in the {team_name} team</event_type>
    <latest_user_message>{{latest_user_message}}</latest_user_message>{linear_issue_context}{parent_comment_context}{external_user_context}{timezone_context}{default_team_context}
    <important_notes>
        - The main focus is to be my latest comment, if I mention anything about this "issue" or "here" I am referring to "this" Linear issue {issue_identifier}.
        - Do not update issue title unless explicitly asked to do so.
        - Update the issue description when asked to make changes or when given clarifications on requirements.
        - Ensure you also read the linear issue {issue_identifier} description and comments to understand the context of the conversation.
    </important_notes>
    <communication_guidelines_and_system_constraints>
    - You should avoid asking me follow up questions, unless absolutely necessary.
    - You should make particular note what the intended deliverable is (If I'm asking for a PR you should create a PR at the end of the task).
     > IMPORTANT: You don't need to use any tools to comment on this linear issue for me to see your messages.
    However if I ask you to explicitly post a comment or update a comment you should use the appropriate tools if available.
    </communication_guidelines_and_system_constraints>
</formatted_context>

{SYSTEM_REMINDERS}
"""

    elif event_type == BLOCKS_EVENT__TRIGGER_ALIAS.GITLAB_ISSUE_COMMENT.value:
        issue = event_data.get("issue", {})
        issue_id = issue.get("id")
        issue_iid = issue.get("iid")
        issue_title = issue.get("title")
        issue_url = issue.get("url", "")

        project = event_data.get("project", {})
        project_name = project.get("name", "")
        project_path = project.get("path_with_namespace", "")

        latest_comment = event_data.get("new_comment", {})
        latest_comment_body = latest_comment.get("body")
        latest_user_message = latest_comment_body
        latest_comment_id = latest_comment.get("id")

        # Build GitLab issue context
        gitlab_issue_context = f"""
    <issue_iid>{issue_iid}</issue_iid>
    <issue_title>{issue_title}</issue_title>
    <issue_url>{issue_url}</issue_url>
    <project_path>{project_path}</project_path>
    <project_name>{project_name}</project_name>"""

        # Check if there's a parent comment (thread context)
        parent_comment = event_data.get("parent_comment", {})
        parent_comment_context = ""
        if parent_comment:
            parent_comment_body = parent_comment.get("body", "")
            parent_comment_author = parent_comment.get("author", {})
            parent_comment_author_name = parent_comment_author.get("name", "")
            parent_comment_id = parent_comment.get("id", "")
            parent_comment_context = f"""
    <parent_comment>
        <note>This comment is part of a threaded discussion. Below is the root comment that started this thread, which may provide important context.</note>
        <parent_comment_id>{parent_comment_id}</parent_comment_id>
        <parent_comment_author>{parent_comment_author_name}</parent_comment_author>
        <parent_comment_body>{parent_comment_body}</parent_comment_body>
    </parent_comment>"""

        formatted_context = f"""
<formatted_context>
    <event_type>I have mentioned you in a GitLab issue #{issue_iid} for the {project_path} project</event_type>
    <latest_user_message>{{latest_user_message}}</latest_user_message>
    <gitlab_issue>{gitlab_issue_context}
        <gitlab_comment_id>My latest message is within GitLab issue comment ID: {latest_comment_id}</gitlab_comment_id>
    </gitlab_issue>{parent_comment_context}{external_user_context}{timezone_context}{default_team_context}
    <important_notes>
        - The main focus is to be my latest comment, if I mention anything about this "issue" I am referring to "this" GitLab issue #{issue_iid} in the project {project_path}.
        - Do not update issue title or description unless explicitly asked to do so by me.
        - Ensure you also read the issue description and comments to understand the context of the conversation.
    </important_notes>
    <communication_guidelines_and_system_constraints>
    - You should avoid asking me follow up questions, unless absolutely necessary.
    - You should make particular note what the intended deliverable is (If I'm asking for a PR you should create a PR at the end of the task).
    > IMPORTANT: You don't need to use any tools to comment on this issue for me to see your messages.
    However if I ask you to explicitly post a comment or update a comment you should use the appropriate tools if available.
    </communication_guidelines_and_system_constraints>
</formatted_context>

{SYSTEM_REMINDERS}
"""

    elif event_type == BLOCKS_EVENT__TRIGGER_ALIAS.GITLAB_MERGE_REQUEST_COMMENT.value:
        merge_request = event_data.get("merge_request", {})
        mr_id = merge_request.get("id")
        mr_iid = merge_request.get("iid")
        mr_title = merge_request.get("title")
        mr_url = merge_request.get("url", "")
        source_branch = merge_request.get("source_branch", "")
        target_branch = merge_request.get("target_branch", "")

        project = event_data.get("project", {})
        project_name = project.get("name", "")
        project_path = project.get("path_with_namespace", "")

        latest_comment = event_data.get("new_comment", {})
        latest_comment_body = latest_comment.get("body")
        latest_user_message = latest_comment_body
        latest_comment_id = latest_comment.get("id")
        latest_commend_diff_hunk = latest_comment.get("diff_hunk", "")
        latest_comment_filename = latest_comment.get("filename", "")

        # if diff hunk too large then truncate it to 1000 characters
        if len(latest_commend_diff_hunk) > 3000:
            latest_commend_diff_hunk = latest_commend_diff_hunk[:3000] + "\n [... truncated diff hunk ...] To view the remainder use `glab` command to view this comment's diff hunk."

        # Build GitLab merge request context
        gitlab_mr_context = f"""
    <merge_request_iid>{mr_iid}</merge_request_iid>
    <merge_request_title>{mr_title}</merge_request_title>
    <merge_request_url>{mr_url}</merge_request_url>
    <source_branch>{source_branch}</source_branch>
    <target_branch>{target_branch}</target_branch>
    <project_path>{project_path}</project_path>
    <project_name>{project_name}</project_name>"""

        # Check if there's a parent comment (thread context)
        parent_comment = event_data.get("parent_comment", {})
        parent_comment_context = ""
        if parent_comment:
            parent_comment_body = parent_comment.get("body", "")
            parent_comment_author = parent_comment.get("author", {})
            parent_comment_author_name = parent_comment_author.get("name", "")
            parent_comment_id = parent_comment.get("id", "")
            parent_comment_context = f"""
    <parent_comment>
        <note>This comment is part of a threaded discussion. Below is the root comment that started this thread, which may provide important context.</note>
        <parent_comment_id>{parent_comment_id}</parent_comment_id>
        <parent_comment_author>{parent_comment_author_name}</parent_comment_author>
        <parent_comment_body>{parent_comment_body}</parent_comment_body>
    </parent_comment>"""

        # Handle changes if available
        changes_context = ""
        changes = event_data.get("changes", [])
        if changes:
            changes_info = []
            for change in changes[:3]:  # Show first 3 changes for context
                changes_info.append(f"- {change.get('new_path', change.get('old_path', 'unknown'))}")
            changes_context = f"""
    <changed_files>
        <note>The following files have been changed in this merge request:</note>
        {"".join(changes_info)}
        {f"<total_files_changed>{len(changes)} files total</total_files_changed>" if len(changes) > 3 else ""}
    </changed_files>"""

        formatted_context = f"""
<formatted_context>
    <event_type>I have mentioned you in GitLab Merge Request {mr_iid} for the {project_path} project. Ensure you are working on the correct branch.</event_type>
    <latest_user_message>
        {{latest_user_message}}
        {f"<referenced_filename>{latest_comment_filename}</referenced_filename>" if latest_comment_filename else ""}
        {f"<referenced_diff_hunk>{latest_commend_diff_hunk}</referenced_diff_hunk>" if latest_commend_diff_hunk else ""}
    </latest_user_message>
    <gitlab_merge_request>{gitlab_mr_context}{changes_context}
        <gitlab_comment_id>My latest message is within GitLab merge request comment ID: {latest_comment_id}</gitlab_comment_id>
    </gitlab_merge_request>{parent_comment_context}{external_user_context}{timezone_context}{default_team_context}
    <important_notes>
        - The main focus is to be my latest comment, if I mention anything about "here" or "this" "merge request" I am referring to "this" GitLab merge request !{mr_iid} in the project {project_path}.
        - Do not update merge request title or description unless explicitly asked to do so by me.
        - Ensure you also read the merge request description and comments to understand the context of the conversation.
        - IMPORTANT: If you are asked to review the merge request, provide feedback on the code changes referenced in the changes section.
    </important_notes>
    <communication_guidelines_and_system_constraints>
    - You should avoid asking me follow up questions, unless absolutely necessary.
    - You should make particular note what the intended deliverable is (If I'm asking for a PR you should create a PR at the end of the task).
    > IMPORTANT: You don't need to use any tools to comment on this merge request for me to see your messages.
    However if I ask you to explicitly post a comment or update a comment you should use the appropriate tools if available.
    </communication_guidelines_and_system_constraints>
</formatted_context>

{SYSTEM_REMINDERS}
"""

    elif event_type == BLOCKS_EVENT__TRIGGER_ALIAS.WEBHOOK.value:

        event = event_data.get("event", {})
        text = event.get("text", "")
        latest_user_message = text

        formatted_context = f"""
<formatted_context>
    <event_type>I have mentioned you in a remote session</event_type>
    <latest_user_message>{{latest_user_message}}</latest_user_message>{external_user_context}{timezone_context}{default_team_context}
    <important_notes>
        The main focus is to be my latest message.
    </important_notes>
    <communication_guidelines_and_system_constraints>
    - You should avoid asking me follow up questions, unless absolutely necessary.
    - You should make particular note what the intended deliverable is (If I'm asking for a PR you should create a PR at the end of the task).
    > IMPORTANT: I can already see your messages, so you don't need to use any tools for me to see your messages unless I explicitly ask you to do so.
    </communication_guidelines_and_system_constraints>
</formatted_context>

{SYSTEM_REMINDERS}
"""

    return formatted_context, latest_user_message
