#!/usr/bin/env python3
"""
邮箱服务器全面测试脚本
- 创建电路设计部门邮箱账号
- 各邮箱互发问候消息（中英双语）
- 测试附件发送功能
"""

import os
import sys
import time
import random
import smtplib
import subprocess
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email import encoders
from pathlib import Path
from typing import List, Dict, Tuple

# 配置
DOMAIN = "lilexx.top"
MAIL_SERVER = "192.3.252.113"
SMTP_PORT = 25

# 现有的商品贸易邮箱
EXISTING_ACCOUNTS = {
    "sales@lilexx.top": "tXFN96M7EdyaCq5",
    "purchase@lilexx.top": "Kyqyi7944JwVNqKA",
    "export@lilexx.top": "31jDMsSpySBhuOG8",
    "import@lilexx.top": "zq8qhB6RKfWUFhb",
    "logistics@lilexx.top": "Ea2Hf7TqICfvPh",
    "trade@lilexx.top": "vxJa5xlnhAi7jmov",
    "info@lilexx.top": "rfedU6Co3vWDa1Q",
    "support@lilexx.top": "gJdk8aJspsHRS5d",
}

# 电路设计部门邮箱账号定义
CIRCUIT_DESIGN_ACCOUNTS = {
    "pcb-design": "PCB Design Team - PCB设计团队",
    "schematic": "Schematic Design - 原理图设计",
    "layout": "Layout Engineering - 布局工程",
    "signal-integrity": "Signal Integrity Analysis - 信号完整性分析",
    "power-design": "Power Circuit Design - 电源电路设计",
    "analog-circuit": "Analog Circuit Design - 模拟电路设计",
    "digital-circuit": "Digital Circuit Design - 数字电路设计",
    "rf-design": "RF Circuit Design - 射频电路设计",
    "embedded-hw": "Embedded Hardware Design - 嵌入式硬件设计",
    "test-validation": "Circuit Testing & Validation - 电路测试与验证",
}

# 业务相关的中英双语问候消息模板
GREETING_TEMPLATES = {
    "sales": {
        "subject": "产品询价与合作机会 / Product Inquiry and Cooperation Opportunity",
        "body": """尊敬的同事，

希望这封邮件能找到您一切安好。我们部门正在寻找优质的贸易合作伙伴，期待与您探讨潜在的业务合作机会和产品供应方案。

Dear Colleague,

I hope this email finds you well. Our department is actively seeking quality trade partners and looking forward to discussing potential business cooperation opportunities and product supply solutions with you.

期待您的回复 / Looking forward to your reply.

最诚挚的问候 / Best Regards"""
    },
    "purchase": {
        "subject": "采购需求确认 / Purchase Requirements Confirmation",
        "body": """您好，

我们正在评估本季度的采购计划，需要确认贵部门对原材料和组件的需求。请提供详细的规格和数量信息以便我们进行市场调研和价格谈判。

Hello,

We are currently evaluating this quarter's procurement plan and need to confirm your department's requirements for raw materials and components. Please provide detailed specifications and quantity information for our market research and price negotiations.

谢谢合作 / Thank you for your cooperation.

采购部 / Purchasing Department"""
    },
    "export": {
        "subject": "出口订单处理进度 / Export Order Processing Update",
        "body": """亲爱的团队成员，

关于最近的出口订单，我们已完成海关文件准备工作。请协助确认货物包装规格是否符合国际运输标准，确保顺利清关和按时交付。

Dear Team Member,

Regarding the recent export orders, we have completed the customs documentation preparation. Please help confirm if the cargo packaging specifications meet international shipping standards to ensure smooth customs clearance and timely delivery.

感谢支持 / Thanks for your support.

出口部 / Export Department"""
    },
    "import": {
        "subject": "进口货物到港通知 / Import Cargo Arrival Notification",
        "body": """尊敬的合作伙伴，

我们的进口货物预计将于下周到港。请提前准备相关的检验检疫文件和仓储安排，确保货物能够及时入库并开始后续的分销流程。

Dear Partner,

Our import cargo is expected to arrive at the port next week. Please prepare relevant inspection and quarantine documents and warehouse arrangements in advance to ensure timely warehousing and subsequent distribution processes.

祝工作顺利 / Wish you smooth work.

进口部 / Import Department"""
    },
    "logistics": {
        "subject": "物流配送方案优化 / Logistics Delivery Optimization Plan",
        "body": """物流团队您好，

为了提高配送效率和降低运输成本，我们建议优化现有的物流路线规划。请审核附件中的新方案并提供反馈意见，以便我们尽快实施改进措施。

Hello Logistics Team,

To improve delivery efficiency and reduce transportation costs, we suggest optimizing the existing logistics route planning. Please review the new proposal in the attachment and provide feedback so we can implement improvements as soon as possible.

期待您的意见 / Looking forward to your feedback.

物流协调部 / Logistics Coordination Department"""
    },
    "trade": {
        "subject": "国际贸易政策更新 / International Trade Policy Update",
        "body": """贸易部门同事们，

最新的国际贸易政策已经发布，其中包含关税调整和进出口许可证要求的重要变更。请仔细阅读相关文件并及时更新我们的业务流程以保持合规性。

Dear Trade Department Colleagues,

The latest international trade policies have been released, including important changes to tariff adjustments and import-export license requirements. Please carefully read the relevant documents and update our business processes promptly to maintain compliance.

共同进步 / Progress together.

贸易管理部 / Trade Management Department"""
    },
    "info": {
        "subject": "公司信息更新通知 / Company Information Update Notice",
        "body": """各位同事，

我们的公司信息和联系方式已更新。请查收附件中的最新版本企业简介和产品目录，在与客户沟通时使用更新后的资料以展示我们的专业形象。

Dear Colleagues,

Our company information and contact details have been updated. Please find the latest version of our company profile and product catalog in the attachment, and use the updated materials when communicating with clients to showcase our professional image.

感谢配合 / Thank you for your cooperation.

信息管理部 / Information Management Department"""
    },
    "support": {
        "subject": "客户支持案例跟进 / Customer Support Case Follow-up",
        "body": """支持团队成员，

我们收到几个重要的客户反馈需要及时处理。请优先解决技术支持工单并在二十四小时内给客户提供初步响应，确保客户满意度和我们的服务质量。

Support Team Members,

We have received several important customer feedbacks that require timely handling. Please prioritize technical support tickets and provide initial responses to customers within twenty-four hours to ensure customer satisfaction and our service quality.

客户至上 / Customer first.

客户支持中心 / Customer Support Center"""
    },
    # 电路设计部门消息模板
    "pcb-design": {
        "subject": "PCB设计评审会议 / PCB Design Review Meeting",
        "body": """PCB设计团队，

下周三将举行本月的PCB设计评审会议。请准备好您的设计文件和仿真结果，我们将讨论信号完整性、电源分配网络和制造工艺可行性等关键问题。

PCB Design Team,

The monthly PCB design review meeting will be held next Wednesday. Please prepare your design files and simulation results, and we will discuss critical issues such as signal integrity, power distribution network, and manufacturing feasibility.

技术精进 / Technical excellence.

PCB设计部 / PCB Design Department"""
    },
    "schematic": {
        "subject": "原理图设计规范更新 / Schematic Design Standard Update",
        "body": """原理图设计工程师们，

公司已更新电路原理图设计规范和符号库标准。请下载最新版本的设计指南并在后续项目中严格遵守，确保设计文档的一致性和可维护性。

Schematic Design Engineers,

The company has updated the circuit schematic design specifications and symbol library standards. Please download the latest version of the design guide and strictly follow it in subsequent projects to ensure consistency and maintainability of design documents.

规范设计 / Standardized design.

原理图设计组 / Schematic Design Group"""
    },
    "layout": {
        "subject": "高速电路布局优化建议 / High-Speed Circuit Layout Optimization",
        "body": """布局工程团队，

针对最新的高速数字电路项目，我们需要特别注意走线阻抗控制和差分对布局。请参考附件中的设计指南并在布局时充分考虑信号串扰和电磁干扰问题。

Layout Engineering Team,

For the latest high-speed digital circuit project, we need to pay special attention to trace impedance control and differential pair layout. Please refer to the design guide in the attachment and fully consider signal crosstalk and electromagnetic interference issues during layout.

精准布局 / Precise layout.

布局工程部 / Layout Engineering Department"""
    },
    "signal-integrity": {
        "subject": "信号完整性分析报告 / Signal Integrity Analysis Report",
        "body": """信号完整性团队，

请对新设计的高速接口电路进行全面的信号完整性仿真分析。重点检查眼图质量、反射和串扰水平，确保所有关键信号满足规格要求后再提交生产。

Signal Integrity Team,

Please conduct comprehensive signal integrity simulation analysis on the newly designed high-speed interface circuit. Focus on checking eye diagram quality, reflection and crosstalk levels, and ensure all critical signals meet specification requirements before submitting for production.

品质保证 / Quality assurance.

信号完整性分析组 / Signal Integrity Analysis Group"""
    },
    "power-design": {
        "subject": "电源电路效率优化方案 / Power Circuit Efficiency Optimization",
        "body": """电源设计工程师，

我们需要提升电源模块的转换效率并降低热耗散。请评估使用新型开关控制器和同步整流技术的可行性，目标是达到百分之九十五以上的效率。

Power Design Engineers,

We need to improve the conversion efficiency of power modules and reduce thermal dissipation. Please evaluate the feasibility of using new switching controllers and synchronous rectification technology, with the goal of achieving over ninety-five percent efficiency.

高效节能 / High efficiency and energy saving.

电源设计部 / Power Design Department"""
    },
    "analog-circuit": {
        "subject": "模拟电路噪声抑制技术 / Analog Circuit Noise Suppression Technology",
        "body": """模拟电路设计团队，

在精密测量应用中，我们遇到了低频噪声干扰问题。请研究采用斩波稳定技术和相关双采样方法来改善信噪比，并提供详细的设计方案和仿真验证结果。

Analog Circuit Design Team,

In precision measurement applications, we encountered low-frequency noise interference issues. Please research using chopper stabilization techniques and correlated double sampling methods to improve signal-to-noise ratio, and provide detailed design proposals and simulation verification results.

精密设计 / Precision design.

模拟电路组 / Analog Circuit Group"""
    },
    "digital-circuit": {
        "subject": "FPGA设计时序收敛优化 / FPGA Design Timing Closure Optimization",
        "body": """数字电路设计团队，

当前FPGA项目在高频时钟域出现时序违规。请检查关键路径并应用流水线技术、寄存器复制和时钟门控等优化方法，确保设计能够稳定运行在目标频率。

Digital Circuit Design Team,

The current FPGA project has timing violations in the high-frequency clock domain. Please check critical paths and apply optimization methods such as pipelining, register replication, and clock gating to ensure the design can run stably at the target frequency.

时序优先 / Timing first.

数字电路部 / Digital Circuit Department"""
    },
    "rf-design": {
        "subject": "射频电路匹配网络设计 / RF Circuit Matching Network Design",
        "body": """射频设计工程师，

新的无线通信模块需要设计高效的阻抗匹配网络。请使用史密斯圆图工具优化匹配电路，确保在整个工作频段内获得良好的回波损耗和插入损耗性能。

RF Design Engineers,

The new wireless communication module requires designing an efficient impedance matching network. Please use Smith Chart tools to optimize the matching circuit and ensure good return loss and insertion loss performance across the entire operating frequency band.

射频专精 / RF expertise.

射频设计组 / RF Design Group"""
    },
    "embedded-hw": {
        "subject": "嵌入式硬件接口设计规范 / Embedded Hardware Interface Design Standard",
        "body": """嵌入式硬件团队，

为了确保微控制器系统的可靠性，请在设计中加入适当的电平转换、ESD保护和去耦电容布局。所有外部接口必须符合相关工业标准并通过EMC测试要求。

Embedded Hardware Team,

To ensure the reliability of microcontroller systems, please include appropriate level translation, ESD protection, and decoupling capacitor layout in the design. All external interfaces must comply with relevant industrial standards and pass EMC test requirements.

可靠第一 / Reliability first.

嵌入式硬件部 / Embedded Hardware Department"""
    },
    "test-validation": {
        "subject": "电路测试计划与验证流程 / Circuit Test Plan and Validation Process",
        "body": """测试验证团队，

请制定详细的电路板测试计划，包括功能测试、环境应力测试和可靠性验证。确保所有测试项目覆盖设计规格要求，并建立完整的测试文档和故障分析报告。

Test and Validation Team,

Please develop a detailed circuit board test plan, including functional testing, environmental stress testing, and reliability validation. Ensure all test items cover design specification requirements, and establish complete test documentation and failure analysis reports.

质量把关 / Quality control.

测试验证中心 / Test and Validation Center"""
    },
}


def generate_password():
    """生成随机密码"""
    return subprocess.check_output(
        "openssl rand -base64 12 | tr -d '/+=' | head -c 16",
        shell=True
    ).decode().strip()


def create_circuit_design_accounts() -> Dict[str, str]:
    """创建电路设计部门邮箱账号"""
    print("="*60)
    print("创建电路设计部门邮箱账号")
    print("Creating Circuit Design Department Email Accounts")
    print("="*60)
    print()

    new_accounts = {}

    for username, description in CIRCUIT_DESIGN_ACCOUNTS.items():
        email = f"{username}@{DOMAIN}"
        password = generate_password()

        print(f"创建账号 / Creating: {email}")
        print(f"  描述 / Description: {description}")

        # 使用 docker exec 创建账号
        cmd = f'docker exec mailserver setup email add "{email}" "{password}"'
        result = subprocess.run(cmd, shell=True, capture_output=True, text=True)

        if result.returncode == 0 or "already exists" in result.stderr.lower():
            print(f"  ✓ 账号创建成功 / Account created")
            new_accounts[email] = password
        else:
            print(f"  ✗ 创建失败 / Failed: {result.stderr}")

        print()
        time.sleep(0.5)

    return new_accounts


def find_test_attachments(max_size=2*1024*1024) -> List[str]:
    """查找合适的测试附件文件"""
    print("查找测试附件文件 / Finding test attachment files...")

    attachment_paths = []

    # 搜索多个目录
    search_dirs = [
        "/opt/google/chrome/locales",
        "/root/mail-server",
        "/etc",
    ]

    for search_dir in search_dirs:
        if os.path.exists(search_dir):
            try:
                for root, dirs, files in os.walk(search_dir):
                    for file in files:
                        filepath = os.path.join(root, file)
                        try:
                            size = os.path.getsize(filepath)
                            if 1024 < size < max_size:  # 1KB ~ 2MB
                                attachment_paths.append(filepath)
                                if len(attachment_paths) >= 20:
                                    break
                        except:
                            continue
                    if len(attachment_paths) >= 20:
                        break
            except:
                continue

    print(f"  找到 {len(attachment_paths)} 个可用文件 / Found {len(attachment_paths)} files")
    return attachment_paths


def send_email_with_attachment(
    from_email: str,
    from_password: str,
    to_email: str,
    subject: str,
    body: str,
    attachment_path: str = None
) -> bool:
    """发送带附件的邮件"""
    try:
        # 创建邮件对象
        msg = MIMEMultipart()
        msg['From'] = from_email
        msg['To'] = to_email
        msg['Subject'] = subject

        # 添加邮件正文
        msg.attach(MIMEText(body, 'plain', 'utf-8'))

        # 添加附件
        if attachment_path and os.path.exists(attachment_path):
            filename = os.path.basename(attachment_path)
            with open(attachment_path, 'rb') as f:
                part = MIMEBase('application', 'octet-stream')
                part.set_payload(f.read())
                encoders.encode_base64(part)
                part.add_header(
                    'Content-Disposition',
                    f'attachment; filename= {filename}'
                )
                msg.attach(part)

        # 连接SMTP服务器并发送
        with smtplib.SMTP(MAIL_SERVER, SMTP_PORT, timeout=30) as server:
            server.set_debuglevel(0)
            # 不使用 STARTTLS 和 认证（因为禁用了SSL）
            # server.starttls()
            # server.login(from_email, from_password)
            server.send_message(msg)

        return True

    except Exception as e:
        print(f"    ✗ 发送失败 / Failed: {str(e)}")
        return False


def test_mail_exchange(all_accounts: Dict[str, str], attachments: List[str]):
    """测试邮箱互发消息"""
    print("\n" + "="*60)
    print("开始邮箱互发测试 / Starting Mail Exchange Test")
    print("="*60)
    print()

    # 等待邮件服务器完全启动
    print("等待邮件服务器就绪 / Waiting for mail server to be ready...")
    time.sleep(10)

    total_sent = 0
    total_failed = 0
    email_list = list(all_accounts.keys())

    # 每个邮箱给其他邮箱发送消息
    for i, from_email in enumerate(email_list):
        from_password = all_accounts[from_email]
        from_username = from_email.split('@')[0]

        # 确定使用哪个消息模板
        template_key = from_username
        if template_key not in GREETING_TEMPLATES:
            # 如果是新的电路设计账号，随机选择一个电路设计模板
            circuit_keys = [k for k in GREETING_TEMPLATES.keys()
                          if k in CIRCUIT_DESIGN_ACCOUNTS]
            if circuit_keys:
                template_key = random.choice(circuit_keys)
            else:
                template_key = "info"

        template = GREETING_TEMPLATES.get(template_key, GREETING_TEMPLATES["info"])

        # 选择1-3个收件人
        num_recipients = min(3, len(email_list) - 1)
        recipients = random.sample(
            [e for e in email_list if e != from_email],
            num_recipients
        )

        print(f"\n发件人 / Sender: {from_email}")
        print(f"收件人 / Recipients: {', '.join(recipients)}")
        print(f"主题 / Subject: {template['subject']}")

        for to_email in recipients:
            # 随机决定是否添加附件
            attachment = random.choice(attachments) if attachments and random.random() > 0.5 else None

            if attachment:
                print(f"  → {to_email} (附件 / with attachment: {os.path.basename(attachment)})")
            else:
                print(f"  → {to_email}")

            success = send_email_with_attachment(
                from_email=from_email,
                from_password=from_password,
                to_email=to_email,
                subject=template['subject'],
                body=template['body'],
                attachment_path=attachment
            )

            if success:
                print(f"    ✓ 发送成功 / Sent successfully")
                total_sent += 1
            else:
                total_failed += 1

            # 避免发送过快
            time.sleep(2)

    print("\n" + "="*60)
    print("邮件发送统计 / Email Sending Statistics")
    print("="*60)
    print(f"成功发送 / Successfully sent: {total_sent}")
    print(f"发送失败 / Failed: {total_failed}")
    print(f"成功率 / Success rate: {total_sent/(total_sent+total_failed)*100:.1f}%")


def save_accounts_to_file(new_accounts: Dict[str, str]):
    """保存新账号信息到文件"""
    output_file = "/root/mail-server/circuit_design_accounts.txt"

    with open(output_file, 'w', encoding='utf-8') as f:
        f.write("="*60 + "\n")
        f.write("电路设计部门邮箱账号 / Circuit Design Department Accounts\n")
        f.write("="*60 + "\n\n")

        for email, password in new_accounts.items():
            username = email.split('@')[0]
            description = CIRCUIT_DESIGN_ACCOUNTS.get(username, "")

            f.write(f"邮箱地址 / Email: {email}\n")
            f.write(f"密码 / Password: {password}\n")
            f.write(f"用途 / Purpose: {description}\n")
            f.write(f"IMAP: mail.{DOMAIN}:993 (SSL)\n")
            f.write(f"SMTP: mail.{DOMAIN}:587 (STARTTLS)\n")
            f.write("-" * 60 + "\n\n")

    print(f"\n账号信息已保存到 / Account info saved to: {output_file}")


def main():
    """主函数"""
    print("="*60)
    print("邮箱服务器全面测试脚本")
    print("Comprehensive Mail Server Test Script")
    print("="*60)
    print()

    # 1. 创建电路设计部门账号
    new_accounts = create_circuit_design_accounts()

    if new_accounts:
        save_accounts_to_file(new_accounts)

    # 2. 合并所有账号
    all_accounts = {**EXISTING_ACCOUNTS, **new_accounts}
    print(f"\n总账号数 / Total accounts: {len(all_accounts)}")

    # 3. 查找测试附件
    attachments = find_test_attachments()

    # 4. 测试邮箱互发
    if len(all_accounts) > 1:
        test_mail_exchange(all_accounts, attachments)
    else:
        print("账号数量不足，跳过邮件互发测试")

    print("\n" + "="*60)
    print("测试完成！/ Test Completed!")
    print("="*60)
    print("\n请检查各邮箱查看收到的邮件 / Please check mailboxes for received emails")
    print(f"Web邮箱访问 / Web Mail: http://{MAIL_SERVER}:8080")


if __name__ == "__main__":
    main()
