#!/usr/bin/env python3

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

def debug_column_mapping():
    """
    檢查10月份的確切欄位對應
    """
    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)
        
        # 檢查10月份第4行的詳細欄位對應
        result = service.spreadsheets().values().get(
            spreadsheetId=SPREADSHEET_ID,
            range='2025年10月!A4:Y4'
        ).execute()
        
        values = result.get('values', [])
        if values:
            row = values[0]
            print(f'10月2日資料詳細分析：')
            print(f'總欄位數: {len(row)}')
            for i, cell in enumerate(row):
                if cell and str(cell).strip():
                    print(f'索引 {i:2d} (欄位{chr(65+i)}): "{cell}"')
        
        # 檢查標題行以了解格式
        result2 = service.spreadsheets().values().get(
            spreadsheetId=SPREADSHEET_ID,
            range='2025年10月!A1:Y2'
        ).execute()
        
        values2 = result2.get('values', [])
        if len(values2) >= 1:
            print(f'\n標題行分析：')
            for row_num, row in enumerate(values2, 1):
                print(f'第{row_num}行標題：')
                for i, cell in enumerate(row):
                    if cell and str(cell).strip():
                        short_title = str(cell).strip()[:20]
                        print(f'  索引 {i:2d} (欄位{chr(65+i)}): "{short_title}"')
                        
        # 檢查11月份的格式對比
        print(f'\n{"="*50}')
        print(f'11月3日資料對比分析：')
        result3 = service.spreadsheets().values().get(
            spreadsheetId=SPREADSHEET_ID,
            range='2025年11月!A5:Y5'
        ).execute()
        
        values3 = result3.get('values', [])
        if values3:
            row = values3[0]
            print(f'總欄位數: {len(row)}')
            for i, cell in enumerate(row):
                if cell and str(cell).strip():
                    print(f'索引 {i:2d} (欄位{chr(65+i)}): "{cell}"')
                    
    except Exception as e:
        print(f'執行失敗：{e}')

if __name__ == '__main__':
    debug_column_mapping()