#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
測試 ms1.pchome.tw SMTP 伺服器
"""

import smtplib
import sys

def test_smtp_detailed(host, ports=[25, 587, 465]):
    """詳細測試 SMTP 伺服器"""

    print("=" * 80)
    print(f"🔍 測試 SMTP 伺服器: {host}")
    print("=" * 80)

    successful_config = None

    for port in ports:
        print(f"\n📡 測試埠號: {port}")
        print("-" * 80)

        try:
            print(f"   正在連接 {host}:{port} ...")
            server = smtplib.SMTP(host, port, timeout=10)

            print(f"   ✅ 連接成功！")

            # 取得伺服器資訊
            response = server.ehlo()
            print(f"   伺服器回應碼: {response[0]}")

            # 檢查支援的功能
            print(f"\n   支援的功能：")
            if server.has_extn('STARTTLS'):
                print(f"      ✅ STARTTLS (加密)")
            if server.has_extn('AUTH'):
                print(f"      ✅ AUTH (認證)")
            if server.has_extn('SIZE'):
                size = server.esmtp_features.get('size', 'unknown')
                print(f"      ✅ SIZE (郵件大小限制: {size})")

            # 測試 STARTTLS
            if server.has_extn('STARTTLS'):
                try:
                    print(f"\n   測試 STARTTLS 加密...")
                    server.starttls()
                    print(f"   ✅ STARTTLS 啟動成功")
                    server.ehlo()  # 重新 EHLO

                    # 記錄成功的設定
                    if not successful_config:
                        successful_config = {
                            'host': host,
                            'port': port,
                            'tls': True
                        }

                except Exception as e:
                    print(f"   ⚠️  STARTTLS 失敗: {e}")

            server.quit()
            print(f"\n   ✅ 埠號 {port} 測試成功")

        except ConnectionRefusedError:
            print(f"   ❌ 連接被拒絕（埠號可能未開放）")
        except Exception as e:
            print(f"   ❌ 錯誤: {e}")

    # 顯示結果
    print("\n" + "=" * 80)
    print("📊 測試結果")
    print("=" * 80)

    if successful_config:
        print(f"\n✅ 找到可用的 SMTP 設定：")
        print(f"   伺服器: {successful_config['host']}")
        print(f"   埠號: {successful_config['port']}")
        print(f"   加密: {'STARTTLS' if successful_config['tls'] else '無'}")

        print(f"\n💡 建議的 .env 設定：")
        print(f"   EMAIL_HOST={successful_config['host']}")
        print(f"   EMAIL_PORT={successful_config['port']}")
        print(f"   EMAIL_HOST_USER=yingpin_chen@pchome.tw")
        print(f"   EMAIL_HOST_PASSWORD=您的密碼")
        print(f"   EMAIL_SENDER=yingpin_chen@pchome.tw")

        return successful_config
    else:
        print(f"\n❌ 所有埠號都無法連接")
        print(f"\n可能需要：")
        print(f"   1. 連接到公司內部網路")
        print(f"   2. 使用 VPN")
        print(f"   3. 確認伺服器地址正確")
        return None

if __name__ == '__main__':
    config = test_smtp_detailed('ms1.pchome.tw')

    if config:
        print("\n" + "=" * 80)
        print("🎉 測試成功！現在可以更新 .env 設定了")
        print("=" * 80)
        sys.exit(0)
    else:
        print("\n" + "=" * 80)
        print("❌ 測試失敗，請檢查網路連線或聯絡 IT 部門")
        print("=" * 80)
        sys.exit(1)
