#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
測試郵件發送功能
直接測試 VendorEmailService 的郵件發送功能
"""

import sys
import os
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))

from database.vendor_manager import VendorDatabaseManager
from database.vendor_models import VendorList, VendorEmail, VendorStockout
from services.vendor_email_service import VendorEmailService

def test_grouped_email():
    """測試按廠商分組發送"""

    print("=" * 60)
    print("測試 1: 按廠商分組發送郵件")
    print("=" * 60)

    db = VendorDatabaseManager()
    session = db.get_session()
    email_service = VendorEmailService()

    try:
        # 查詢測試廠商 TEST_V001
        vendor = session.query(VendorList).filter_by(vendor_code='TEST_V001').first()
        if not vendor:
            print("❌ 找不到測試廠商 TEST_V001")
            return

        # 查詢該廠商的郵件
        emails = session.query(VendorEmail).filter_by(vendor_id=vendor.id).all()
        vendor_emails = [e.email for e in emails if e.is_active]

        if not vendor_emails:
            print("❌ 廠商沒有郵件地址")
            return

        # 查詢該廠商的缺貨商品
        stockouts = session.query(VendorStockout).filter_by(
            vendor_code='TEST_V001',
            status='pending'
        ).all()

        if not stockouts:
            print("❌ 沒有待發送的缺貨商品")
            return

        print(f"\n廠商: {vendor.vendor_name} ({vendor.vendor_code})")
        print(f"郵件地址: {', '.join(vendor_emails)}")
        print(f"缺貨商品數: {len(stockouts)}")
        print(f"\n商品清單:")
        for stockout in stockouts:
            print(f"  - {stockout.product_name} ({stockout.product_code})")

        # 確認發送
        print("\n" + "-" * 60)
        response = input("確定要發送測試郵件嗎？(y/n): ")
        if response.lower() != 'y':
            print("已取消")
            return

        # 發送郵件
        print("\n開始發送...")
        result = email_service.send_vendor_grouped_email(
            vendor_code=vendor.vendor_code,
            vendor_name=vendor.vendor_name,
            vendor_emails=vendor_emails,
            stockout_items=stockouts,
            batch_id='TEST_BATCH_001'
        )

        if result['success']:
            print(f"\n✅ 郵件發送成功！")
            print(f"   主旨: {result['subject']}")
            print(f"   收件者: {', '.join(result['recipients'])}")
            print(f"   商品數: {result['product_count']}")
            if result.get('attachment_filename'):
                print(f"   附件: {result['attachment_filename']}")
        else:
            print(f"\n❌ 郵件發送失敗: {result['error']}")

    except Exception as e:
        print(f"\n❌ 測試失敗: {e}")
        import traceback
        traceback.print_exc()
    finally:
        session.close()


def test_single_email():
    """測試按商品單筆發送"""

    print("\n\n" + "=" * 60)
    print("測試 2: 按商品單筆發送郵件")
    print("=" * 60)

    db = VendorDatabaseManager()
    session = db.get_session()
    email_service = VendorEmailService()

    try:
        # 查詢一個測試缺貨商品
        stockout = session.query(VendorStockout).filter_by(
            vendor_code='TEST_V002',
            status='pending'
        ).first()

        if not stockout:
            print("❌ 找不到測試缺貨商品")
            return

        # 查詢廠商
        vendor = session.query(VendorList).filter_by(vendor_code=stockout.vendor_code).first()
        if not vendor:
            print("❌ 找不到廠商")
            return

        # 查詢廠商郵件
        emails = session.query(VendorEmail).filter_by(vendor_id=vendor.id).all()
        vendor_emails = [e.email for e in emails if e.is_active]

        if not vendor_emails:
            print("❌ 廠商沒有郵件地址")
            return

        print(f"\n廠商: {vendor.vendor_name} ({vendor.vendor_code})")
        print(f"郵件地址: {', '.join(vendor_emails)}")
        print(f"商品: {stockout.product_name} ({stockout.product_code})")

        # 確認發送
        print("\n" + "-" * 60)
        response = input("確定要發送測試郵件嗎？(y/n): ")
        if response.lower() != 'y':
            print("已取消")
            return

        # 發送郵件
        print("\n開始發送...")
        result = email_service.send_single_item_email(
            vendor_code=vendor.vendor_code,
            vendor_name=vendor.vendor_name,
            vendor_emails=vendor_emails,
            stockout_item=stockout,
            batch_id='TEST_BATCH_002'
        )

        if result['success']:
            print(f"\n✅ 郵件發送成功！")
            print(f"   主旨: {result['subject']}")
            print(f"   收件者: {', '.join(result['recipients'])}")
            print(f"   商品: {result['product_name']}")
        else:
            print(f"\n❌ 郵件發送失敗: {result['error']}")

    except Exception as e:
        print(f"\n❌ 測試失敗: {e}")
        import traceback
        traceback.print_exc()
    finally:
        session.close()


if __name__ == '__main__':
    print("\n" + "=" * 60)
    print("廠商缺貨郵件發送功能測試")
    print("=" * 60)
    print("\n⚠️  注意：此測試會實際發送郵件到 vincentn_chen@chohome.tw")
    print("   請確保 SMTP 設定正確\n")

    # 測試 1: 分組發送
    test_grouped_email()

    # 測試 2: 單筆發送
    test_single_email()

    print("\n" + "=" * 60)
    print("測試完成")
    print("=" * 60)
