"""Email sending via Gmail SMTP or SendGrid."""

from __future__ import annotations

import logging
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

from src.config.settings import EmailConfig

logger = logging.getLogger("seo_optimizer")


def send_smtp(
    config: EmailConfig,
    subject: str,
    html_body: str,
    to_addresses: list[str] | None = None,
) -> bool:
    """Send email via SMTP (Gmail TLS).

    Args:
        config: Email configuration.
        subject: Email subject.
        html_body: HTML body content.
        to_addresses: Override recipients (defaults to config.email_to).

    Returns:
        True if sent successfully, False otherwise.
    """
    recipients = to_addresses or config.email_to
    if not recipients:
        logger.warning("No email recipients configured — skipping send")
        return False

    if not config.smtp_user or not config.smtp_password:
        logger.warning("SMTP credentials not configured — skipping send")
        return False

    msg = MIMEMultipart("alternative")
    msg["Subject"] = subject
    msg["From"] = config.email_from or config.smtp_user
    msg["To"] = ", ".join(recipients)
    msg.attach(MIMEText(html_body, "html", "utf-8"))

    try:
        with smtplib.SMTP(config.smtp_host, config.smtp_port) as server:
            server.ehlo()
            server.starttls()
            server.ehlo()
            server.login(config.smtp_user, config.smtp_password)
            server.sendmail(msg["From"], recipients, msg.as_string())

        logger.info("Email sent via SMTP to %s: %s", recipients, subject)
        return True
    except Exception as e:
        logger.error("SMTP send failed: %s", e)
        return False


def send_sendgrid(
    config: EmailConfig,
    subject: str,
    html_body: str,
    to_addresses: list[str] | None = None,
) -> bool:
    """Send email via SendGrid HTTP API.

    Args:
        config: Email configuration.
        subject: Email subject.
        html_body: HTML body content.
        to_addresses: Override recipients (defaults to config.email_to).

    Returns:
        True if sent successfully, False otherwise.
    """
    recipients = to_addresses or config.email_to
    if not recipients:
        logger.warning("No email recipients configured — skipping send")
        return False

    if not config.sendgrid_api_key:
        logger.warning("SendGrid API key not configured — skipping send")
        return False

    try:
        from sendgrid import SendGridAPIClient
        from sendgrid.helpers.mail import Mail

        message = Mail(
            from_email=config.sendgrid_from or config.email_from,
            to_emails=recipients,
            subject=subject,
            html_content=html_body,
        )

        sg = SendGridAPIClient(config.sendgrid_api_key)
        response = sg.send(message)

        logger.info(
            "Email sent via SendGrid (status %d) to %s: %s",
            response.status_code, recipients, subject,
        )
        return response.status_code in (200, 201, 202)
    except Exception as e:
        logger.error("SendGrid send failed: %s", e)
        return False


def send_email(
    config: EmailConfig,
    subject: str,
    html_body: str,
    to_addresses: list[str] | None = None,
) -> bool:
    """Send email using the configured method (SendGrid if available, else SMTP).

    Args:
        config: Email configuration.
        subject: Email subject.
        html_body: HTML body content.
        to_addresses: Override recipients.

    Returns:
        True if sent successfully, False otherwise.
    """
    if config.use_sendgrid:
        return send_sendgrid(config, subject, html_body, to_addresses)
    return send_smtp(config, subject, html_body, to_addresses)
