#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Google Drive 連接測試腳本
"""

import sys
import os

# 確保可以導入專案模組
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))

from services.google_drive_service import drive_service
from services.import_service import import_service


def main():
    print("=" * 60)
    print("Google Drive 連接測試")
    print("=" * 60)
    print()

    # 測試 1: 認證
    print("🔐 步驟 1: 測試 Google Drive 認證...")
    if drive_service.authenticate():
        print("✅ 認證成功！")
    else:
        print("❌ 認證失敗！")
        print("   請確認 config/google_credentials.json 檔案存在")
        return
    print()

    # 測試 2: 取得配置
    print("⚙️ 步驟 2: 讀取匯入配置...")
    folder_path = import_service.get_config('gdrive_folder_path', '業績報表/當日業績')
    file_pattern = import_service.get_config('gdrive_file_pattern', '即時業績_當日')
    print(f"   資料夾路徑: {folder_path}")
    print(f"   檔案模式: {file_pattern}")
    print()

    # 測試 3: 列出檔案
    print("📁 步驟 3: 列出 Google Drive 檔案...")
    files = drive_service.list_files_in_folder(folder_path, file_pattern)

    if files:
        print(f"✅ 找到 {len(files)} 個檔案：")
        for i, file in enumerate(files, 1):
            print(f"   {i}. {file['name']}")
            print(f"      ID: {file['id']}")
            print(f"      大小: {file.get('size', 'N/A')} bytes")
            print(f"      修改時間: {file.get('modifiedTime', 'N/A')}")
            print()
    else:
        print("⚠️  沒有找到符合條件的檔案")
        print()
        print("💡 提示:")
        print("   1. 確認 Google Drive 資料夾路徑正確")
        print("   2. 確認資料夾中有 Excel 檔案")
        print("   3. 檔案名稱是否包含指定的模式")
    print()

    # 測試 4: 查詢最近的匯入任務
    print("📊 步驟 4: 查詢最近的匯入任務...")
    jobs = import_service.get_recent_jobs(limit=5)

    if jobs:
        print(f"✅ 找到 {len(jobs)} 個最近的任務：")
        for job in jobs:
            status_emoji = {
                'pending': '⏳',
                'downloading': '⬇️',
                'importing': '📥',
                'completed': '✅',
                'failed': '❌'
            }.get(job['status'], '❓')

            print(f"   {status_emoji} 任務 {job['id']}: {job['status']}")
            print(f"      檔案: {job.get('drive_file_name', 'N/A')}")
            print(f"      進度: {job.get('progress_percent', 0)}%")
            print(f"      成功: {job.get('success_rows', 0)} 筆")
            if job.get('error_message'):
                print(f"      錯誤: {job['error_message']}")
            print()
    else:
        print("ℹ️  尚無匯入記錄")
    print()

    print("=" * 60)
    print("測試完成！")
    print("=" * 60)
    print()
    print("🌐 開啟網頁介面查看詳細資訊:")
    print("   http://localhost/auto_import")
    print()


if __name__ == "__main__":
    try:
        main()
    except KeyboardInterrupt:
        print("\n\n❌ 使用者中斷測試")
        sys.exit(1)
    except Exception as e:
        print(f"\n\n❌ 測試過程發生錯誤: {str(e)}")
        import traceback
        traceback.print_exc()
        sys.exit(1)
