import os
import sys
from sqlalchemy import inspect, text

# ================= 環境設定 =================
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, BASE_DIR)

try:
    from database.manager import DatabaseManager
except ImportError as e:
    print(f"❌ 無法導入模組: {e}")
    print("請確認您已安裝所有套件 (pip install -r requirements.txt) 並在專案根目錄執行。")
    sys.exit(1)

def check_data():
    print("🔍 正在檢查資料庫狀態...")
    try:
        db = DatabaseManager()
        engine = db.engine
        inspector = inspect(engine)
        tables = inspector.get_table_names()
        
        print(f"📂 資料庫路徑: {engine.url}")
        print(f"📑 資料表清單: {tables}")
        print("-" * 30)

        with engine.connect() as conn:
            for table in tables:
                try:
                    count = conn.execute(text(f"SELECT COUNT(*) FROM {table}")).scalar()
                    print(f"✅ {table:<25} : {count} 筆")
                except Exception as e:
                    print(f"❌ {table:<25} : 讀取錯誤 ({e})")
        
        print("-" * 30)
        print("檢查完成。")

    except Exception as e:
        print(f"🚨 資料庫連線失敗: {e}")

if __name__ == "__main__":
    check_data()