#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
快速查詢郵件發送狀態
"""

import sys
from pathlib import Path

PROJECT_ROOT = Path(__file__).resolve().parents[2]
sys.path.insert(0, str(PROJECT_ROOT))

from database.vendor_manager import VendorDatabaseManager
from database.vendor_models import EmailSendLog
from datetime import datetime, timedelta

def check_email_status():
    """查詢最近的郵件發送狀態"""

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

    try:
        # 查詢最近 7 天的發送記錄
        since = datetime.now() - timedelta(days=7)
        logs = session.query(EmailSendLog).filter(
            EmailSendLog.created_at >= since
        ).order_by(EmailSendLog.created_at.desc()).all()

        if not logs:
            print("\n❌ 最近 7 天沒有郵件發送記錄")
            print("\n💡 提示：")
            print("   1. 請先在網頁上選擇缺貨商品並點擊「按廠商發送」或「按商品發送」")
            print("   2. 或者執行測試腳本：python3 test_email_send.py")
            return

        print("\n" + "=" * 80)
        print(f"📧 最近 7 天郵件發送記錄 (共 {len(logs)} 筆)")
        print("=" * 80)

        # 統計
        success_count = sum(1 for log in logs if log.status == 'sent')
        failed_count = sum(1 for log in logs if log.status == 'failed')
        pending_count = sum(1 for log in logs if log.status == 'pending')

        print(f"\n📊 統計：")
        print(f"   ✅ 成功: {success_count}")
        print(f"   ❌ 失敗: {failed_count}")
        print(f"   ⏳ 待發送: {pending_count}")

        if success_count > 0:
            rate = (success_count / len(logs)) * 100
            print(f"   📈 成功率: {rate:.1f}%")

        print(f"\n📋 詳細記錄：")
        print("-" * 80)

        for log in logs[:20]:  # 只顯示最近 20 筆
            status_icon = "✅" if log.status == 'sent' else "❌" if log.status == 'failed' else "⏳"

            print(f"\n{status_icon} ID: {log.id} | 批次: {log.batch_id}")
            print(f"   收件者: {log.recipient_email}")
            print(f"   主旨: {log.subject}")
            print(f"   商品數: {log.product_count}")
            print(f"   狀態: {log.status}")
            print(f"   時間: {log.sent_at or log.created_at}")

            if log.error_message:
                print(f"   ⚠️  錯誤: {log.error_message}")

            if log.attachment_filename:
                print(f"   📎 附件: {log.attachment_filename}")

        if len(logs) > 20:
            print(f"\n... 還有 {len(logs) - 20} 筆記錄（請使用網頁查看完整記錄）")

        # 提示如何確認
        print("\n" + "=" * 80)
        print("💡 如何確認對方真的收到郵件？")
        print("=" * 80)
        print("1. 登入收件信箱檢查：yingpin_chen@pchome.tw")
        print("2. 檢查垃圾郵件資料夾（第一次發送可能被誤判）")
        print("3. 查看網頁記錄：http://localhost/vendor-stockout/send-email")
        print("\n⚠️  注意：")
        print("   - 狀態「成功」= Gmail SMTP 已接收郵件")
        print("   - 但不保證對方信箱一定收到（可能被退信或進垃圾桶）")
        print("   - 建議先發測試郵件到自己的信箱確認格式")
        print("=" * 80)

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


if __name__ == '__main__':
    check_email_status()
