"""
邮件服务

提供邮件发送功能，用于：
- 密码重置邮件
- 用户通知邮件
- 系统告警邮件

支持 SMTP 协议，可配置多种邮件服务商（阿里云、腾讯云、SendGrid 等）。
"""

import logging
import os
import smtplib
import ssl
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from typing import Optional, Dict, Any
from pathlib import Path

from jinja2 import Template

from src.config.settings import NODE_ENV

logger = logging.getLogger(__name__)

# 邮件配置（从环境变量读取）
SMTP_HOST = os.getenv('SMTP_HOST', '')
SMTP_PORT = int(os.getenv('SMTP_PORT', '587'))
SMTP_USER = os.getenv('SMTP_USER', '')
SMTP_PASSWORD = os.getenv('SMTP_PASSWORD', '')
SMTP_FROM = os.getenv('SMTP_FROM', '')
SMTP_TLS = os.getenv('SMTP_TLS', 'true').lower() == 'true'

# 前端重置密码页面 URL
FRONTEND_URL = os.getenv('FRONTEND_URL', 'http://localhost:3000')

# 邮件模板目录
TEMPLATES_DIR = Path(__file__).parent.parent / "templates" / "email"


# 默认邮件模板
PASSWORD_RESET_TEMPLATE = """
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <style>
        body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; line-height: 1.6; color: #333; }
        .container { max-width: 600px; margin: 0 auto; padding: 20px; }
        .header { background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; padding: 30px; text-align: center; border-radius: 8px 8px 0 0; }
        .content { background: #f9f9f9; padding: 30px; border-radius: 0 0 8px 8px; }
        .button { display: inline-block; background: #667eea; color: white; padding: 12px 30px; text-decoration: none; border-radius: 5px; margin: 20px 0; }
        .footer { text-align: center; color: #999; font-size: 12px; margin-top: 20px; }
        .code { background: #e9ecef; padding: 15px; border-radius: 5px; font-family: monospace; font-size: 18px; letter-spacing: 2px; text-align: center; margin: 20px 0; }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>🔐 密码重置</h1>
        </div>
        <div class="content">
            <p>您好 {{ username }}，</p>
            <p>我们收到了您的密码重置请求。请点击下方按钮重置密码：</p>
            <div style="text-align: center;">
                <a href="{{ reset_url }}" class="button">重置密码</a>
            </div>
            <p>或者复制以下链接到浏览器：</p>
            <p style="word-break: break-all; color: #667eea;">{{ reset_url }}</p>
            <p>此链接将在 <strong>{{ expires_in }} 小时</strong> 后失效。</p>
            <hr style="border: none; border-top: 1px solid #ddd; margin: 20px 0;">
            <p style="color: #666; font-size: 14px;">
                如果您没有请求重置密码，请忽略此邮件。您的账户安全不会受到影响。
            </p>
        </div>
        <div class="footer">
            <p>Pixel AI 视频创作平台</p>
            <p>此邮件由系统自动发送，请勿回复</p>
        </div>
    </div>
</body>
</html>
"""

WELCOME_TEMPLATE = """
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <style>
        body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; line-height: 1.6; color: #333; }
        .container { max-width: 600px; margin: 0 auto; padding: 20px; }
        .header { background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; padding: 30px; text-align: center; border-radius: 8px 8px 0 0; }
        .content { background: #f9f9f9; padding: 30px; border-radius: 0 0 8px 8px; }
        .button { display: inline-block; background: #667eea; color: white; padding: 12px 30px; text-decoration: none; border-radius: 5px; margin: 20px 0; }
        .footer { text-align: center; color: #999; font-size: 12px; margin-top: 20px; }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>🎉 欢迎加入 Pixel</h1>
        </div>
        <div class="content">
            <p>您好 {{ username }}，</p>
            <p>欢迎加入 Pixel AI 视频创作平台！您的账户已成功创建。</p>
            <div style="text-align: center;">
                <a href="{{ login_url }}" class="button">开始使用</a>
            </div>
            <p>开始创作您的第一个 AI 视频吧！</p>
        </div>
        <div class="footer">
            <p>Pixel AI 视频创作平台</p>
        </div>
    </div>
</body>
</html>
"""


class EmailService:
    """邮件服务"""

    _instance = None

    def __new__(cls):
        if cls._instance is None:
            cls._instance = super().__new__(cls)
        return cls._instance

    def __init__(self):
        self.enabled = bool(SMTP_HOST and SMTP_USER and SMTP_PASSWORD)
        if not self.enabled:
            logger.warning(
                "Email service is disabled. "
                "Set SMTP_HOST, SMTP_USER, SMTP_PASSWORD to enable."
            )

    def _load_template(self, template_name: str, default_template: str) -> Template:
        """加载邮件模板"""
        template_path = TEMPLATES_DIR / f"{template_name}.html"
        if template_path.exists():
            return Template(template_path.read_text(encoding='utf-8'))
        return Template(default_template)

    async def send_email(
        self,
        to_email: str,
        subject: str,
        html_content: str,
        text_content: Optional[str] = None
    ) -> Dict[str, Any]:
        """
        发送邮件

        Args:
            to_email: 收件人邮箱
            subject: 邮件主题
            html_content: HTML 内容
            text_content: 纯文本内容（可选）

        Returns:
            发送结果
        """
        if not self.enabled:
            logger.warning(f"Email service disabled. Would send to {to_email}: {subject}")
            return {
                "success": False,
                "error": "Email service not configured",
                "message": "邮件服务未配置"
            }

        try:
            # 创建邮件
            msg = MIMEMultipart('alternative')
            msg['Subject'] = subject
            msg['From'] = SMTP_FROM or SMTP_USER
            msg['To'] = to_email

            # 添加纯文本内容
            if text_content:
                msg.attach(MIMEText(text_content, 'plain', 'utf-8'))

            # 添加 HTML 内容
            msg.attach(MIMEText(html_content, 'html', 'utf-8'))

            # 发送邮件
            context = ssl.create_default_context()

            with smtplib.SMTP(SMTP_HOST, SMTP_PORT) as server:
                if SMTP_TLS:
                    server.starttls(context=context)
                server.login(SMTP_USER, SMTP_PASSWORD)
                server.send_message(msg)

            logger.info(f"Email sent successfully to {to_email}: {subject}")
            return {
                "success": True,
                "to": to_email,
                "subject": subject
            }

        except Exception as e:
            logger.error(f"Failed to send email to {to_email}: {e}")
            return {
                "success": False,
                "error": str(e),
                "message": "邮件发送失败"
            }

    async def send_password_reset(
        self,
        to_email: str,
        username: str,
        reset_token: str,
        expires_in: int = 1
    ) -> Dict[str, Any]:
        """
        发送密码重置邮件

        Args:
            to_email: 收件人邮箱
            username: 用户名
            reset_token: 重置令牌
            expires_in: 过期时间（小时）

        Returns:
            发送结果
        """
        # 构建重置链接
        reset_url = f"{FRONTEND_URL}/reset-password?token={reset_token}"

        # 加载模板
        template = self._load_template('password_reset', PASSWORD_RESET_TEMPLATE)

        # 渲染 HTML
        html_content = template.render(
            username=username,
            reset_url=reset_url,
            reset_token=reset_token,
            expires_in=expires_in,
            frontend_url=FRONTEND_URL
        )

        # 纯文本版本
        text_content = f"""
您好 {username}，

我们收到了您的密码重置请求。请访问以下链接重置密码：

{reset_url}

此链接将在 {expires_in} 小时后失效。

如果您没有请求重置密码，请忽略此邮件。

Pixel AI 视频创作平台
"""

        return await self.send_email(
            to_email=to_email,
            subject="Pixel - 密码重置",
            html_content=html_content,
            text_content=text_content
        )

    async def send_welcome(
        self,
        to_email: str,
        username: str
    ) -> Dict[str, Any]:
        """
        发送欢迎邮件

        Args:
            to_email: 收件人邮箱
            username: 用户名

        Returns:
            发送结果
        """
        login_url = f"{FRONTEND_URL}/login"

        # 加载模板
        template = self._load_template('welcome', WELCOME_TEMPLATE)

        # 渲染 HTML
        html_content = template.render(
            username=username,
            login_url=login_url,
            frontend_url=FRONTEND_URL
        )

        # 纯文本版本
        text_content = f"""
您好 {username}，

欢迎加入 Pixel AI 视频创作平台！您的账户已成功创建。

点击以下链接开始使用：
{login_url}

开始创作您的第一个 AI 视频吧！

Pixel AI 视频创作平台
"""

        return await self.send_email(
            to_email=to_email,
            subject="欢迎加入 Pixel",
            html_content=html_content,
            text_content=text_content
        )

    def get_status(self) -> Dict[str, Any]:
        """获取邮件服务状态"""
        return {
            "enabled": self.enabled,
            "host": SMTP_HOST,
            "port": SMTP_PORT,
            "user": SMTP_USER,
            "from": SMTP_FROM or SMTP_USER,
            "tls": SMTP_TLS,
            "frontend_url": FRONTEND_URL
        }


# 全局服务实例
email_service = EmailService()
