import psycopg2
from config import Config

def fix_db():
    # 从 SQLALCHEMY_DATABASE_URI 提取连接信息
    # 格式: postgresql://user:pass@host:port/db
    uri = Config.SQLALCHEMY_DATABASE_URI
    print(f"🔗 正在尝试连接数据库...")
    
    try:
        conn = psycopg2.connect(uri)
        cur = conn.cursor()
        
        # 检查并添加 points 字段
        cur.execute("""
            DO $$ 
            BEGIN 
                IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name='users' AND column_name='points') THEN
                    ALTER TABLE users ADD COLUMN points INTEGER DEFAULT 2;
                END IF;
            END $$;
        """)
        
        conn.commit()
        cur.close()
        conn.close()
        print("✅ 数据库字段 points 处理完成 (默认值 2)")
        
    except Exception as e:
        print(f"❌ 数据库修复失败: {e}")

if __name__ == "__main__":
    fix_db()
