# cSpell:ignore momo
import os
import sys
import pandas as pd # type: ignore
from sqlalchemy import create_engine, inspect

# 設定路徑
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
DB_PATH = os.path.join(BASE_DIR, 'data', 'momo_database.db')

def inspect_columns():
    print("🔍 正在檢視資料庫欄位結構...")
    if not os.path.exists(DB_PATH):
        print(f"❌ 資料庫檔案不存在: {DB_PATH}")
        return

    try:
        engine = create_engine(f"sqlite:///{DB_PATH}")
        inspector = inspect(engine)
        table_name = 'realtime_sales_monthly'

        if table_name not in inspector.get_table_names():
            print(f"❌ 找不到資料表: {table_name}")
            return

        # 1. 列出所有欄位
        columns = [col['name'] for col in inspector.get_columns(table_name)]
        print(f"\n📋 資料表 [{table_name}] 包含以下 {len(columns)} 個欄位:")
        print("-" * 50)
        for i, col in enumerate(columns):
            print(f"{i+1}. {col}")
        print("-" * 50)

        # 2. 顯示前 3 筆資料範例 (幫助判斷欄位內容)
        print("\n📊 資料範例 (前 3 筆):")
        df = pd.read_sql(f"SELECT * FROM {table_name} LIMIT 3", engine)
        print(df.to_string())
        print("-" * 50)
        
        # 3. 特別檢查是否有訂單編號相關欄位
        potential_order_ids = [c for c in columns if '訂單' in c or '編號' in c or 'ID' in c or 'No' in c]
        if potential_order_ids:
            print(f"💡 發現可能的訂單編號欄位: {potential_order_ids}")
        else:
            print("⚠️ 未發現明顯的訂單編號欄位 (可能無法計算真實客單價)")

    except Exception as e:
        print(f"❌ 讀取失敗: {e}")

if __name__ == "__main__":
    inspect_columns()
