#!/usr/bin/env python3

from google.oauth2 import service_account
from googleapiclient.discovery import build

def test_processing_flow():
    """
    模擬整個處理流程，檢查每個步驟
    """
    SPREADSHEET_ID = '12dg8UjMTUh8SFPS-X4v83aIwNUEm5CYEKO3RNUW7QCA'
    
    try:
        creds = service_account.Credentials.from_service_account_file(
            'service_account_key.json',
            scopes=['https://www.googleapis.com/auth/spreadsheets.readonly']
        )
        
        service = build('sheets', 'v4', credentials=creds)
        
        # 模擬工作表列表
        monthly_sheet_names = [
            '2025年1月工時紀錄', '2025年2月工時紀錄', '2025年3月工時紀錄',
            '2025年4月工時紀錄', '2025年5月工時紀錄', '2025年6月工時紀錄',
            '2025年7月', '2025年8月', '2025年9月', '2025年10月', '2025年11月'
        ]
        
        # 獲取實際存在的工作表
        spreadsheet_metadata = service.spreadsheets().get(spreadsheetId=SPREADSHEET_ID).execute()
        existing_sheets = [s['properties']['title'] for s in spreadsheet_metadata.get('sheets', [])]
        
        print('處理流程模擬：')
        print('='*60)
        
        total_found = 0
        for sheet_name in monthly_sheet_names:
            print(f'\n處理工作表: {sheet_name}')
            
            if sheet_name not in existing_sheets:
                print(f'  ❌ 工作表不存在')
                continue
                
            print(f'  ✓ 工作表存在')
            
            # 格式檢測
            if '年1月' in sheet_name or '年2月' in sheet_name or '年3月' in sheet_name or '年4月' in sheet_name or '年5月' in sheet_name:
                format_type = '1-5月格式'
            elif '年6月' in sheet_name:
                format_type = '6月格式'
            elif '年7月' in sheet_name or '年8月' in sheet_name or '年9月' in sheet_name or '年10月' in sheet_name or '年11月' in sheet_name:
                format_type = '7+月格式'
            else:
                format_type = '未知格式'
                
            print(f'  格式類型: {format_type}')
            
            # 讀取數據
            try:
                result = service.spreadsheets().values().get(
                    spreadsheetId=SPREADSHEET_ID,
                    range=f'{sheet_name}!A1:Z50'
                ).execute()
                
                values = result.get('values', [])
                print(f'  數據行數: {len(values)}')
                
                # 簡單檢查是否有工作時數 > 7.25 的記錄
                potential_overtime = 0
                
                if format_type == '1-5月格式':
                    # 檢查F欄（扣除午晚休後的工時）
                    for row in values[1:]:  # 跳過標題
                        if len(row) > 5 and row[5]:
                            try:
                                work_hours = float(row[5])
                                if work_hours > 7.25:
                                    potential_overtime += 1
                            except:
                                pass
                                
                elif format_type == '6月格式':
                    # 檢查G欄（當日合計）
                    for row in values[2:]:  # 跳過前兩行
                        if len(row) > 6 and row[6]:
                            try:
                                work_hours = float(row[6])
                                if work_hours > 7.25:
                                    potential_overtime += 1
                            except:
                                pass
                                
                elif format_type == '7+月格式':
                    # 檢查H欄（工時小計）或I欄（當日合計）
                    for row in values[2:]:  # 跳過前兩行
                        if len(row) > 7 and row[7]:
                            try:
                                work_hours = float(row[7])
                                if work_hours > 7.25:
                                    potential_overtime += 1
                            except:
                                pass
                
                print(f'  可能加班記錄: {potential_overtime} 筆')
                total_found += potential_overtime
                
            except Exception as e:
                print(f'  ❌ 讀取失敗: {e}')
        
        print(f'\n總結：')
        print(f'預期可能的加班記錄總數: {total_found} 筆')
        print(f'實際程式產生的記錄數: 從加班費紀錄總表中可以看到約20筆')
        
        if total_found > 20:
            print(f'⚠️ 可能有 {total_found - 20} 筆記錄沒有被正確處理')
        
    except Exception as e:
        print(f'執行失敗：{e}')

if __name__ == '__main__':
    test_processing_flow()