"""
Route exit node for the CodeAct agent.

This node is the final destination for the agent graph, serving as a post-run hook.
"""

import os
from datetime import datetime
from typing import TYPE_CHECKING, Literal

from langchain_core.runnables import RunnableConfig
from langgraph.types import Command
from loguru import logger

from universal_mcp.agents.codeact0.llm_tool import ruzo_email_notification
from universal_mcp.agents.codeact0.state import CodeActState

if TYPE_CHECKING:
    from universal_mcp.agents.codeact0.agent import CodeActPlaybookAgent


def create_route_exit_node(agent_instance: "CodeActPlaybookAgent"):
    """
    Factory function that creates the route_exit node with access to agent instance.

    Args:
        agent_instance: The CodeActPlaybookAgent instance

    Returns:
        The route_exit node function
    """

    async def route_exit(state: CodeActState, config: RunnableConfig) -> Command[Literal["__end__"]]:
        """
        Exit point for the CodeAct agent graph.
        """
        is_scheduled_run = config["configurable"].get("is_scheduled_run", False)
        if is_scheduled_run:
            try:
                logger.info("Scheduled run completed, sending email notification...")
                # Fetch user email using the registry client
                if agent_instance.registry and agent_instance.registry.client:
                    user_info = await agent_instance.registry.client.me()
                    user_email = user_info.get("email")

                    if user_email:
                        thread_id = config["configurable"].get("thread_id")
                        frontend_url = os.getenv("FRONTEND_URL", "https://ruzo.ai")
                        html_content = f"""
                                <div style="font-family: sans-serif; max-width: 600px; margin: 0 auto; padding: 20px; border: 1px solid #e0e0e0; border-radius: 8px; background-color: white;">
                                    <div style="text-align: center; border-bottom: 1px solid #eee; padding-bottom: 20px; margin-bottom: 20px;">
                                        <h2 style="margin: 0; color: #333;">Task Completed Successfully</h2>
                                    </div>
                                    <div style="padding: 10px 0; text-align: center;">
                                        <p style="font-size: 16px; color: #555; margin-bottom: 25px;">Your scheduled automation run has finished! You can review the full chat and outputs in your Ruzo chat, using the following link.</p>
                                        <a href="{frontend_url}/chat?threadId={thread_id}" style="display: inline-block; background-color: #000; color: #fff; text-decoration: none; padding: 12px 24px; border-radius: 6px; font-weight: 600; font-size: 14px;">View Chat</a>
                                    </div>
                                    <div style="margin-top: 30px; border-top: 1px solid #eee; padding-top: 20px; text-align: center; color: #999; font-size: 12px;">
                                        <p>This is an automated message from Ruzo.</p>
                                    </div>
                                </div>
                                """

                        await ruzo_email_notification(
                            subject="Your scheduled task has completed", html_content=html_content, to_email=user_email
                        )
                    else:
                        logger.warning("Could not fetch user email for notification")
                else:
                    logger.warning("Registry client not available for fetching user info")

            except Exception as e:
                logger.error(f"Failed to send email notification: {e}")

        elif agent_instance.run_start_time and (datetime.now() - agent_instance.run_start_time).total_seconds() > 300:
            try:
                logger.info("Run took longer than 5 minutes, sending email notification...")
                # Fetch user email using the registry client
                if agent_instance.registry and agent_instance.registry.client:
                    user_info = await agent_instance.registry.client.me()
                    user_email = user_info.get("email")

                    if user_email:
                        thread_id = config["configurable"].get("thread_id")
                        frontend_url = os.getenv("FRONTEND_URL", "https://ruzo.ai")
                        html_content = f"""
                                <div style="font-family: sans-serif; max-width: 600px; margin: 0 auto; padding: 20px; border: 1px solid #e0e0e0; border-radius: 8px; background-color: white;">
                                    <div style="text-align: center; border-bottom: 1px solid #eee; padding-bottom: 20px; margin-bottom: 20px;">
                                        <h2 style="margin: 0; color: #333;">Task Completed</h2>
                                    </div>
                                    <div style="padding: 10px 0; text-align: center;">
                                        <p style="font-size: 16px; color: #555; margin-bottom: 25px;">Your long-running task has finished! You can review the full chat and outputs in your Ruzo chat, using the following link.</p>
                                        <a href="{frontend_url}/chat?threadId={thread_id}" style="display: inline-block; background-color: #000; color: #fff; text-decoration: none; padding: 12px 24px; border-radius: 6px; font-weight: 600; font-size: 14px;">View Chat</a>
                                    </div>
                                    <div style="margin-top: 30px; border-top: 1px solid #eee; padding-top: 20px; text-align: center; color: #999; font-size: 12px;">
                                        <p>This is an automated message from Ruzo.</p>
                                    </div>
                                </div>
                                """

                        await ruzo_email_notification(
                            subject="Your task has completed", html_content=html_content, to_email=user_email
                        )
                    else:
                        logger.warning("Could not fetch user email for notification")
                else:
                    logger.warning("Registry client not available for fetching user info")

            except Exception as e:
                logger.error(f"Failed to send email notification: {e}")

        logger.debug("route_exit: Run completed")
        return Command()

    return route_exit
