import os
import json
import re
import logging

logger = logging.getLogger("gmail_mcp")


def clean_content(content: str) -> str:
    """Clean up email content."""
    if content == '[No body content]':
        return ''

    # Remove email signatures
    content = re.split(r'--+|_{2,}', content)[0]

    # Remove quoted text (lines starting with >)
    lines = [line for line in content.split(
        '\n') if not line.strip().startswith('>')]

    # Remove lines containing "wrote:" or dates
    lines = [line for line in lines if not ('wrote:' in line.lower() or
                                            'on ' in line.lower() or
                                            '@' in line)]

    # Remove extra whitespace and empty lines
    lines = [line.strip() for line in lines]
    lines = [line for line in lines if line]

    return '\n'.join(lines).strip()


def clean_name(name: str) -> str:
    """Clean up name format."""
    name = re.sub(r'<[^>]+>', '', name)
    name = re.sub(r'[\w\.-]+@[\w\.-]+\.\w+', '', name)
    return name.strip(' ,.') or 'Anonymous'


def analyze_threads(threads_dir: str = "email_threads", output_file: str = "email_analysis.md") -> None:
    """Organize email threads into a readable document."""

    threads = []
    for filename in os.listdir(threads_dir):
        if filename.endswith('.json'):
            with open(os.path.join(threads_dir, filename), 'r', encoding='utf-8') as f:
                thread_data = json.load(f)
                if thread_data['messages']:
                    threads.append(thread_data)

    with open(output_file, 'w', encoding='utf-8') as f:
        for thread in threads:
            if thread['subject']:
                f.write(f"## {thread['subject']}\n")

            messages = thread['messages']
            for msg in messages:
                sender = clean_name(msg['from'])
                content = clean_content(msg['content'])

                if content:  # Only write if there's actual content
                    if sender == 'me':
                        f.write(f"**me**:\n```\n{content}\n```\n\n")
                    else:
                        f.write(f"**{sender}**:\n```\n{content}\n```\n\n")

            f.write("---\n\n")


if __name__ == "__main__":
    analyze_threads()
    logger.info("Document generated! Check email_analysis.md for results.")
