import os
import json
import shutil
from typing import List
from dotenv import load_dotenv
import logging

# Load environment variables
load_dotenv()

logger = logging.getLogger("gmail_mcp")


def should_delete_thread(thread_data: dict) -> bool:
    """
    Determine if a thread should be deleted based on criteria:
    1. Only one message
    2. Message is from me
    3. No body content
    """
    messages = thread_data.get('messages', [])

    # Check if there's only one message
    if len(messages) != 1:
        return False

    message = messages[0]
    # Check if it's from me and has no content
    return (message.get('from') == 'me' and
            message.get('content') == '[No body content]')


def clean_email_threads(threads_dir: str = "email_threads") -> None:
    """
    Clean up email threads by removing empty single-message threads.
    """
    try:
        if not os.path.exists(threads_dir):
            logger.error(f"Directory {threads_dir} does not exist!")
            return

        # Get master index path
        master_index_path = os.path.join(threads_dir, 'master_index.json')

        if not os.path.exists(master_index_path):
            logger.error("Master index file not found!")
            return

        # Load master index
        with open(master_index_path, 'r', encoding='utf-8') as f:
            master_index = json.load(f)

        threads_to_delete: List[str] = []

        # Track statistics
        total_threads = len(master_index['threads'])
        deleted_count = 0

        logger.info(f"Analyzing {total_threads} threads...")

        # Identify threads to delete
        for thread_id, thread_info in master_index['threads'].items():
            thread_path = os.path.join(threads_dir, thread_info['filename'])

            if os.path.exists(thread_path):
                with open(thread_path, 'r', encoding='utf-8') as f:
                    thread_data = json.load(f)

                if should_delete_thread(thread_data):
                    threads_to_delete.append(thread_id)
                    deleted_count += 1

        # Delete identified threads and update master index
        for thread_id in threads_to_delete:
            # Delete thread file
            thread_filename = master_index['threads'][thread_id]['filename']
            thread_path = os.path.join(threads_dir, thread_filename)

            if os.path.exists(thread_path):
                os.remove(thread_path)

            # Remove from master index threads
            thread_info = master_index['threads'].pop(thread_id)

            # Remove from contacts
            for email in thread_info['participants']:
                if email in master_index['contacts']:
                    contact = master_index['contacts'][email]
                    contact['threads'].remove(thread_id)
                    contact['thread_count'] -= 1

                    # Remove contact if no more threads
                    if contact['thread_count'] == 0:
                        master_index['contacts'].pop(email)

        # Save updated master index
        with open(master_index_path, 'w', encoding='utf-8') as f:
            json.dump(master_index, f, indent=2, ensure_ascii=False)

        logger.info("\nCleanup complete!")
        logger.info(f"Deleted {deleted_count} empty threads")
        logger.info(f"Remaining threads: {len(master_index['threads'])}")
        logger.info(f"Remaining contacts: {len(master_index['contacts'])}")

    except Exception as e:
        logger.error(f"An error occurred: {str(e)}")


if __name__ == "__main__":
    clean_email_threads()
