#!/usr/bin/env python3

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

def debug_parsing():
    """
    調試每個月份的解析結果
    """
    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)
        
        # 要檢查的月份
        months_to_check = ['2025年6月工時紀錄', '2025年7月', '2025年10月', '2025年11月']
        
        for month in months_to_check:
            print(f'{"="*60}')
            print(f'檢查 {month} 的數據結構：')
            print('='*60)
            
            try:
                # 讀取前20行數據
                result = service.spreadsheets().values().get(
                    spreadsheetId=SPREADSHEET_ID,
                    range=f'{month}!A1:Z20'
                ).execute()
                
                values = result.get('values', [])
                if not values:
                    print('沒有找到資料')
                    continue
                
                print(f'總共 {len(values)} 行數據')
                
                # 分析日期行的模式
                date_rows = []
                for i, row in enumerate(values):
                    if len(row) > 1 and row[1]:  # B欄有內容
                        cell_b = str(row[1]).strip()
                        if '2025' in cell_b:
                            date_rows.append((i+1, cell_b, len([c for c in row if c and str(c).strip()])))
                
                if date_rows:
                    print(f'\n找到 {len(date_rows)} 個可能的日期行：')
                    for row_num, date_str, non_empty_cols in date_rows[:5]:  # 只顯示前5個
                        print(f'  第{row_num:2d}行: "{date_str[:40]}" (有效欄位數: {non_empty_cols})')
                else:
                    print('\n❌ 沒有找到包含2025的日期行')
                
                # 檢查是否有打卡時間數據
                time_data = []
                for i, row in enumerate(values):
                    if len(row) > 4:
                        # 檢查D欄和E欄是否像時間
                        d_col = str(row[3]).strip() if len(row) > 3 and row[3] else ''
                        e_col = str(row[4]).strip() if len(row) > 4 and row[4] else ''
                        
                        if ':' in d_col and ':' in e_col:
                            time_data.append((i+1, d_col, e_col))
                
                if time_data:
                    print(f'\n找到 {len(time_data)} 行打卡時間數據：')
                    for row_num, clock_in, clock_out in time_data[:3]:  # 只顯示前3個
                        print(f'  第{row_num:2d}行: {clock_in} - {clock_out}')
                else:
                    print('\n❌ 沒有找到有效的打卡時間數據')
                    
            except Exception as e:
                print(f'❌ 無法讀取 {month}: {e}')
            
            print()  # 空行分隔
                
    except Exception as e:
        print(f'執行失敗：{e}')

if __name__ == '__main__':
    debug_parsing()