"""Email tools."""

from pydantic_ai import RunContext
from pydantic_ai.toolsets import FunctionToolset

from pydanticai_multiagent.dependencies import BaseDeps

email_toolset: FunctionToolset[BaseDeps] = FunctionToolset()


@email_toolset.tool
async def send_email(
    ctx: RunContext[BaseDeps],
    to: str,
    subject: str,
    body: str,
    cc: str | None = None,
) -> str:
    """Send an email.

    Args:
        ctx: The run context with dependencies.
        to: Recipient email address.
        subject: Email subject line.
        body: Email body content.
        cc: Optional CC recipients (comma-separated).
    """
    # In production, integrate with email service (SendGrid, SES, etc.)
    payload = {
        "to": to,
        "subject": subject,
        "body": body,
    }
    if cc:
        payload["cc"] = cc

    response = await ctx.deps.http_client.post(
        "https://api.email-service.example.com/send",
        json=payload,
    )

    if response.status_code == 200:
        return f"Email sent successfully to {to}"
    else:
        return f"Failed to send email: {response.text}"


@email_toolset.tool
async def create_draft(
    ctx: RunContext[BaseDeps],
    to: str,
    subject: str,
    body: str,
) -> str:
    """Create an email draft for review.

    Args:
        ctx: The run context with dependencies.
        to: Intended recipient email address.
        subject: Email subject line.
        body: Email body content.
    """
    # Store draft in database
    await ctx.deps.db.execute(
        """
        INSERT INTO email_drafts (user_id, recipient, subject, body, created_at)
        VALUES ($1, $2, $3, $4, NOW())
        """,
        ctx.deps.user_id,
        to,
        subject,
        body,
    )

    return f"""Draft created:
To: {to}
Subject: {subject}

{body}

(Use 'send_draft' to send this email)"""


@email_toolset.tool
def format_email_template(
    template_name: str,
    variables: dict[str, str],
) -> str:
    """Format an email using a predefined template.

    Args:
        template_name: Name of the template (welcome, reminder, notification).
        variables: Variables to substitute in the template.
    """
    templates = {
        "welcome": """Hello {name},

Welcome to our platform! We're excited to have you on board.

Best regards,
The Team""",
        "reminder": """Hi {name},

This is a friendly reminder about: {topic}

Please take action by {deadline}.

Best,
The Team""",
        "notification": """Hi {name},

{message}

Best,
The Team""",
    }

    template = templates.get(template_name)
    if not template:
        return f"Unknown template: {template_name}. Available: {list(templates.keys())}"

    try:
        return template.format(**variables)
    except KeyError as e:
        return f"Missing variable in template: {e}"
