from __future__ import annotations

import logging
import os
from typing import Any

import httpx

from app.modules.core.domain.ports.notification_port import EmailNotificationPort

logger = logging.getLogger("dscons.infrastructure.adapter.brevo")

BREVO_API_KEY = os.getenv(
    "BREVO_API_KEY",
    "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",
)
BREVO_SENDER_EMAIL = os.getenv("BREVO_SENDER_EMAIL", "admin@dinhsonconstruction.com")
BREVO_SENDER_NAME = os.getenv("BREVO_SENDER_NAME", "DSCons Enterprise")


class BrevoEmailAdapter(EmailNotificationPort):
    """Secondary (Driven) Adapter implementing EmailNotificationPort via Brevo REST API v3."""

    def __init__(
        self,
        api_key: str | None = None,
        default_sender_email: str | None = None,
        default_sender_name: str | None = None,
        timeout_seconds: float = 8.0,
    ) -> None:
        self._api_key = api_key or BREVO_API_KEY
        self._sender_email = default_sender_email or BREVO_SENDER_EMAIL
        self._sender_name = default_sender_name or BREVO_SENDER_NAME
        self._timeout = timeout_seconds

    async def send_email(
        self,
        recipient_email: str,
        subject: str,
        html_content: str,
        recipient_name: str = "DSCons User",
        sender_email: str | None = None,
        sender_name: str | None = None,
        attachments: list[dict[str, str]] | None = None,
    ) -> dict[str, Any]:
        """Sends an email via Brevo REST API v3."""
        payload: dict[str, Any] = {
            "sender": {
                "name": sender_name or self._sender_name,
                "email": sender_email or self._sender_email,
            },
            "to": [{"email": recipient_email, "name": recipient_name}],
            "subject": subject,
            "htmlContent": html_content,
        }

        if attachments:
            payload["attachment"] = attachments

        headers = {
            "accept": "application/json",
            "api-key": self._api_key,
            "content-type": "application/json",
        }

        try:
            async with httpx.AsyncClient(timeout=self._timeout) as client:
                response = await client.post(
                    "https://api.brevo.com/v3/smtp/email",
                    json=payload,
                    headers=headers,
                )
                if response.status_code == 201:
                    data = response.json()
                    logger.info(
                        "Sent email successfully via Brevo to %s: %s",
                        recipient_email,
                        data.get("messageId"),
                    )
                    return {"success": True, "message_id": data.get("messageId")}

                logger.error(
                    "Failed to send email via Brevo: HTTP %s - %s",
                    response.status_code,
                    response.text,
                )
                return {
                    "success": False,
                    "error": response.text,
                    "status_code": response.status_code,
                }
        except Exception as exc:
            logger.error("Exception occurred while sending email via Brevo: %s", exc)
            return {"success": False, "error": str(exc)}
