# discord_tools/scripts/message_deletor.py

import os
import sys
import json
import time

# Add the parent directory to the Python path
script_dir = os.path.dirname(os.path.abspath(__file__))
project_root = os.path.dirname(os.path.dirname(script_dir))
sys.path.insert(0, project_root)

from discord_tools.config.settings import MAX_MESSAGES_PER_REQUEST, ERROR_MESSAGES
from discord_tools.utils.api_utils import make_discord_request, get_user_id

def search_messages_in_channel(channel_id, user_id):
    """
    Search for messages from a specific user in a channel.
    
    :param channel_id: The ID of the channel to search
    :param user_id: The ID of the user whose messages to search for
    :return: List of message objects
    """
    messages = []
    offset = 0
    while True:
        endpoint = f'/channels/{channel_id}/messages/search?author_id={user_id}&offset={offset}'
        response = make_discord_request('GET', endpoint)
        
        if not response:
            print(f"Failed to search messages in channel {channel_id}")
            break
        
        data = response.json()
        total_results = data.get('total_results', 0)
        messages.extend(msg for msg_group in data.get('messages', []) for msg in msg_group)
        print(f"Found {len(messages)} messages. Total: {len(messages)}/{total_results}")
        
        if len(messages) >= total_results or not data.get('messages'):
            break
        
        offset += MAX_MESSAGES_PER_REQUEST
        time.sleep(1)  # Small delay between searches
    
    return messages

def delete_message(channel_id, message_id):
    """
    Delete a specific message.
    
    :param channel_id: The ID of the channel containing the message
    :param message_id: The ID of the message to delete
    :return: True if deletion was successful, False otherwise
    """
    endpoint = f'/channels/{channel_id}/messages/{message_id}'
    response = make_discord_request('DELETE', endpoint)
    
    if response:
        print(f"Successfully deleted message {message_id} in channel {channel_id}")
        return True
    else:
        print(f"Failed to delete message {message_id} in channel {channel_id}")
        return False

def delete_messages_search_method(channel_id, user_id):
    """
    Delete all messages from a specific user in a channel using the search method.
    
    :param channel_id: The ID of the channel to delete messages from
    :param user_id: The ID of the user whose messages to delete
    :return: Number of messages deleted
    """
    print(f"Deleting messages using search method in channel {channel_id}")
    messages = search_messages_in_channel(channel_id, user_id)
    messages_deleted = 0
    
    for message in messages:
        if delete_message(channel_id, message['id']):
            messages_deleted += 1
    
    print(f"Deleted {messages_deleted} messages in channel {channel_id}")
    return messages_deleted

def delete_messages_bulk_method(channel_id, user_id):
    """
    Delete all messages from a specific user in a channel using the bulk method.
    
    :param channel_id: The ID of the channel to delete messages from
    :param user_id: The ID of the user whose messages to delete
    :return: Number of messages deleted
    """
    print(f"Deleting messages using bulk method in channel {channel_id}")
    messages_deleted = 0
    last_message_id = None

    while True:
        endpoint = f'/channels/{channel_id}/messages?limit=100'
        if last_message_id:
            endpoint += f'&before={last_message_id}'
        
        response = make_discord_request('GET', endpoint)
        
        if not response:
            print(f"Failed to fetch messages in channel {channel_id}")
            break
        
        messages = response.json()
        if not messages:
            print(f"No more messages to delete in channel {channel_id}")
            break
        
        user_messages = [msg for msg in messages if msg['author']['id'] == user_id]
        for message in user_messages:
            if delete_message(channel_id, message['id']):
                messages_deleted += 1
        
        last_message_id = messages[-1]['id']
        time.sleep(1)  # Small delay between bulk fetches

    print(f"Deleted {messages_deleted} messages in channel {channel_id}")
    return messages_deleted

def main():
    user_id = get_user_id()
    if not user_id:
        print(ERROR_MESSAGES["api_error"])
        return

    print(f"User ID: {user_id}")

    while True:
        print("\nChoose a deletion method:")
        print("1. Search method (more thorough, but slower)")
        print("2. Bulk method (faster, but might miss some messages in large channels)")
        print("3. Exit")
        
        choice = input("Enter your choice (1, 2, or 3): ").strip()
        
        if choice == '3':
            print("Exiting the program.")
            break
        elif choice not in ['1', '2']:
            print("Invalid choice. Please enter 1, 2, or 3.")
            continue

        delete_method = delete_messages_search_method if choice == '1' else delete_messages_bulk_method

        while True:
            channel_id = input("Enter a channel ID to delete messages from (or press Enter to go back to method selection): ").strip()
            if not channel_id:
                break
            delete_method(channel_id, user_id)

    print("Message deletion process completed.")

if __name__ == "__main__":
    main()