import asyncio
import os
from gmail_mcp.utils.GCP.gmail_auth import get_gmail_service
from gmail_mcp.utils.style_initalization.gmail_indexer import setup_email_index
from gmail_mcp.utils.style_initalization.clean_threads import clean_email_threads
from gmail_mcp.utils.style_initalization.analyze_threads import analyze_threads
from gmail_mcp.utils.openrouter.openrouter_utils import make_api_call
from gmail_mcp.utils.openrouter.prompts import speech_type_analysis


async def analyze_writing_style(test_mode=False):
    """
    Complete pipeline to analyze email writing style:
    1. Index emails (skip in test mode)
    2. Clean threads (skip in test mode)
    3. Create analysis document (skip in test mode)
    4. Generate writing style description

    Args:
        test_mode (bool): If True, skips email processing and uses existing email_analysis.md
    """
    try:
        if not test_mode:
            print("\n1. Initializing Gmail service and indexing emails...")
            service = get_gmail_service()
            setup_email_index(service)

            print("\n2. Cleaning empty threads...")
            clean_email_threads()

            print("\n3. Creating analysis document...")
            analyze_threads()

        # Get the current directory
        current_dir = os.path.dirname(os.path.abspath(__file__))
        email_analysis_path = os.path.join(current_dir, 'email_analysis.md')

        print("\n4. Analyzing writing style...")
        # Check if analysis file exists
        if not os.path.exists(email_analysis_path):
            raise FileNotFoundError(
                f"Could not find email_analysis.md at {email_analysis_path}")

        # Read the analysis file
        with open(email_analysis_path, 'r', encoding='utf-8') as f:
            email_content = f.read()

        # Combine prompt with content
        full_prompt = f"{speech_type_analysis}\n\nHere is the email content to analyze:\n\n{email_content}"

        # Get the analysis from the API
        analysis = await make_api_call(
            prompt=full_prompt,
            model="anthropic/claude-3.5-sonnet",
            temperature=0.7
        )

        # Save the analysis
        writing_style_path = os.path.join(current_dir, 'writing_style.txt')
        with open(writing_style_path, 'w', encoding='utf-8') as f:
            f.write(analysis)

        print("\nAnalysis complete! Check writing_style.txt for results.")

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


if __name__ == "__main__":
    asyncio.run(analyze_writing_style(test_mode=False))
