"""
意见反馈邮件发送模块
通过 SMTP 发送用户反馈到管理员邮箱，支持图片附件
"""
import smtplib
import logging
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email import encoders
from typing import List, Tuple
from .config import settings

logger = logging.getLogger(__name__)

# 反馈类型映射
FEEDBACK_TYPE_MAP = {
    "bug": "Bug 报告",
    "suggestion": "功能建议",
    "other": "其他",
}


def send_feedback_email(
    feedback_type: str,
    content: str,
    contact: str = "",
    username: str = "",
    attachments: List[Tuple[str, bytes]] = None,
) -> bool:
    """
    发送意见反馈邮件

    Args:
        feedback_type: 反馈类型 (bug/suggestion/other)
        content: 反馈内容
        contact: 联系方式（可选）
        username: 当前登录用户名
        attachments: 附件列表，每项为 (文件名, 文件内容bytes)

    Returns:
        是否发送成功
    """
    if not settings.SMTP_USER or not settings.SMTP_PASSWORD:
        logger.error("SMTP 配置不完整，请在 .env 中配置 SMTP_USER 和 SMTP_PASSWORD")
        return False

    to_addr = settings.SMTP_TO or settings.SMTP_USER

    # 构建邮件内容
    type_name = FEEDBACK_TYPE_MAP.get(feedback_type, feedback_type)
    subject = f"[执法助手反馈] {type_name}"

    body_lines = [
        f"反馈类型：{type_name}",
        f"反馈用户：{username or '未知'}",
        f"联系方式：{contact or '未填写'}",
        "",
        "─" * 40,
        "",
        content,
        "",
        "─" * 40,
        "此邮件由综合执法智能辅助系统自动发送",
    ]
    body = "\n".join(body_lines)

    # 构建邮件
    msg = MIMEMultipart()
    msg["From"] = settings.SMTP_USER
    msg["To"] = to_addr
    msg["Subject"] = subject
    msg.attach(MIMEText(body, "plain", "utf-8"))

    # 添加附件
    if attachments:
        for filename, file_data in attachments:
            part = MIMEBase("application", "octet-stream")
            part.set_payload(file_data)
            encoders.encode_base64(part)
            part.add_header(
                "Content-Disposition",
                f'attachment; filename="{filename}"',
            )
            msg.attach(part)

    # 发送
    try:
        if settings.SMTP_PORT == 465:
            server = smtplib.SMTP_SSL(settings.SMTP_HOST, settings.SMTP_PORT, timeout=15)
        else:
            server = smtplib.SMTP(settings.SMTP_HOST, settings.SMTP_PORT, timeout=15)
            server.starttls()

        server.login(settings.SMTP_USER, settings.SMTP_PASSWORD)
        server.sendmail(settings.SMTP_USER, [to_addr], msg.as_string())
        server.quit()

        logger.info(f"反馈邮件已发送: {type_name} -> {to_addr}")
        return True

    except smtplib.SMTPAuthenticationError:
        logger.error("SMTP 认证失败，请检查授权码是否正确")
        return False
    except Exception as e:
        logger.error(f"发送反馈邮件失败: {e}")
        return False
