"""Example of using Gmail with service account authentication."""

import asyncio
import logging
from datetime import datetime
from typing import Optional

from pymailai.agent import EmailAgent
from pymailai.gmail import ServiceAccountCredentials
from pymailai.gmail_client import GmailClient
from pymailai.message import EmailData

# Configure logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

# Path to the service account key file downloaded from Google Cloud Console
SERVICE_ACCOUNT_FILE = "credentials.json"

# The email address of the user to impersonate (must be set up in Google Workspace)
USER_EMAIL = "do@example.com"

# Scopes required for the Gmail API
SCOPES = ["https://www.googleapis.com/auth/gmail.modify"]

# Optional: Custom email address for replies (if different from USER_EMAIL)
CUSTOM_EMAIL = None  # e.g. "custom@example.com"

# Optional: Feedback email configuration
FEEDBACK_EMAIL = "feedback@example.com"
FEEDBACK_MESSAGE = "\n\nPS: You can always send your feedback to feedback@example.com"


async def echo_handler(message: EmailData) -> Optional[EmailData]:
    """Handle incoming emails by echoing their content back."""
    logger.info(f"Processing email from: {message.from_address}, subject: {message.subject}")

    # Create reply with original content
    reply_text = f"""
I received your email with subject: {message.subject}

Here's what you sent:
-------------------
{message.body_text}
-------------------

{FEEDBACK_MESSAGE if FEEDBACK_EMAIL else ""}
"""

    # Create reply email with proper HTML formatting
    reply_html = f"""
<p>I received your email with subject: {message.subject}</p>

<p>Here's what you sent:</p>
<blockquote style="border-left: 2px solid #ccc; margin-left: 0; padding-left: 1em;">
{message.body_html if message.body_html else message.body_text}
</blockquote>

{f'<p>{FEEDBACK_MESSAGE}</p>' if FEEDBACK_EMAIL else ''}
"""

    logger.info("Creating reply email")
    reply = EmailData(
        message_id="",  # Will be generated by Gmail
        subject=f"Re: {message.subject}",
        from_address="",  # Will be set by Gmail
        to_addresses=[message.from_address],
        cc_addresses=[],
        body_text=reply_text,
        body_html=reply_html,
        timestamp=datetime.now(),
        in_reply_to=message.message_id
    )

    logger.info(f"Created reply to: {reply.to_addresses[0]}, subject: {reply.subject}")
    return reply


async def main():
    """Run the email echo service using service account authentication."""
    try:
        # Load service account credentials and set up delegation
        # The service account JSON is downloaded from Google Cloud Console
        # and contains fields like:
        # {
        #   "type": "service_account",
        #   "project_id": "your-project",
        #   "private_key_id": "...",
        #   "private_key": "-----BEGIN PRIVATE KEY-----\n...",
        #   "client_email": "service@project.iam.gserviceaccount.com",
        #   "client_id": "...",
        #   "auth_uri": "https://accounts.google.com/o/oauth2/auth",
        #   "token_uri": "https://oauth2.googleapis.com/token",
        #   ...
        # }

        # Set up Gmail service account authentication
        creds = ServiceAccountCredentials(
            credentials_path=SERVICE_ACCOUNT_FILE,
            delegated_email=USER_EMAIL,
            scopes=SCOPES
        )

        # Create Gmail client
        service = creds.get_gmail_service()
        logger.info(f"Gmail service initialized for {USER_EMAIL}")

        client = GmailClient(service)
        logger.info("Gmail client created")

        # Create and start the email agent
        agent = EmailAgent(client, message_handler=echo_handler)
        logger.info("Email agent created with echo handler")

        async with agent:
            # Keep the agent running
            while True:
                await asyncio.sleep(1)

    except KeyboardInterrupt:
        logger.info("Shutting down email echo service")
    except Exception as e:
        logger.error(f"Service error: {e}")


if __name__ == "__main__":
    asyncio.run(main())
