import psycopg2
from psycopg2.extras import RealDictCursor

# 💡 資料庫連線設定 (請確認密碼與步驟一設定的相同)
DB_CONFIG = {
    "dbname": "cmts_nms",
    "user": "swpa",
    "password": "swpa4920",  # 替換為您的密碼
    "host": "127.0.0.1",     # 如果 DB 在同一台機器上
    "port": "5432"
}

def init_database():
    try:
        # 建立連線
        print("🔄 正在連線到 PostgreSQL...")
        conn = psycopg2.connect(**DB_CONFIG)
        cursor = conn.cursor()

        # 1. 建立 CLI 字典表 (Global-Ready Schema)
        print("🛠️ 正在建立 cli_schema_dictionary 資料表...")
        cursor.execute("""
            CREATE TABLE IF NOT EXISTS cli_schema_dictionary (
                id SERIAL PRIMARY KEY,
                path VARCHAR(255) UNIQUE NOT NULL,
                node_type VARCHAR(50) DEFAULT 'leaf',
                options JSONB DEFAULT '[]'::jsonb,
                description TEXT,
                updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
            );
            CREATE INDEX IF NOT EXISTS idx_cli_schema_path ON cli_schema_dictionary(path);
        """)

        # 2. 建立系統狀態表
        print("🛠️ 正在建立 system_metadata 資料表...")
        cursor.execute("""
            CREATE TABLE IF NOT EXISTS system_metadata (
                key VARCHAR(50) PRIMARY KEY,
                value VARCHAR(255) NOT NULL,
                updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
            );
        """)

        # 3. 寫入初始狀態預設值 (使用 ON CONFLICT 避免重複執行時報錯)
        print("📝 寫入系統狀態預設值...")
        cursor.execute("""
            INSERT INTO system_metadata (key, value) 
            VALUES ('last_schema_sync_time', '1970-01-01 00:00:00')
            ON CONFLICT (key) DO NOTHING;
            
            INSERT INTO system_metadata (key, value) 
            VALUES ('last_schema_sync_cos_version', 'Unknown')
            ON CONFLICT (key) DO NOTHING;
        """)

        # 提交變更並關閉連線
        conn.commit()
        cursor.close()
        conn.close()
        print("✅ 資料庫初始化完成！所有資料表已準備就緒。")

    except Exception as e:
        print(f"❌ 資料庫初始化失敗: {e}")

if __name__ == "__main__":
    init_database()
