#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
檢查 Excel 檔案格式
"""

import pandas as pd
import sys

def check_excel_format(excel_path):
    """檢查 Excel 格式"""

    print("=" * 80)
    print(f"檢查 Excel 檔案格式")
    print("=" * 80)

    try:
        # 讀取 Excel
        df = pd.read_excel(excel_path)

        print(f"\n📊 Excel 資訊：")
        print(f"   總行數: {len(df)}")
        print(f"   總欄位數: {len(df.columns)}")

        print(f"\n📋 所有欄位名稱：")
        for i, col in enumerate(df.columns, 1):
            print(f"   {i:2d}. {col}")

        print(f"\n📄 第一行原始數據：")
        print("-" * 80)
        for col in df.columns:
            value = df[col].iloc[0]
            value_type = type(value).__name__
            print(f"   {col}: {value} (類型: {value_type})")

        # 特別檢查日期相關欄位
        print(f"\n📅 日期欄位詳細資訊：")
        print("-" * 80)

        date_columns = ['當前日期', '缺貨日期']
        for col in date_columns:
            if col in df.columns:
                value = df[col].iloc[0]
                print(f"\n   欄位: {col}")
                print(f"      原始值: {value}")
                print(f"      類型: {type(value)}")
                print(f"      是否為 NaT: {pd.isna(value)}")

                # 嘗試轉換
                try:
                    converted = pd.to_datetime(value, errors='coerce')
                    print(f"      轉換後: {converted}")
                    if pd.notna(converted):
                        print(f"      轉換為日期: {converted.date()}")
                except Exception as e:
                    print(f"      轉換失敗: {e}")

        print("\n" + "=" * 80)

    except Exception as e:
        print(f"\n❌ 錯誤: {e}")
        import traceback
        traceback.print_exc()

if __name__ == '__main__':
    if len(sys.argv) < 2:
        print("使用方式: python3 check_excel_format.py <Excel檔案路徑>")
        print("\n請提供您的 Excel 檔案路徑")
        sys.exit(1)

    excel_path = sys.argv[1]
    check_excel_format(excel_path)
