import os
import psycopg2
import glob

def apply_migrations():
    conn_str = "postgres://postgres:123@152.53.120.181:55432/saveinmed"
    try:
        conn = psycopg2.connect(conn_str)
        conn.autocommit = True
        cur = conn.cursor()
        
        # Pasta de migrations local
        migration_dir = r"C:\dev\saveinmed\backend\internal\repository\postgres\migrations"
        sql_files = sorted(glob.glob(os.path.join(migration_dir, "*.sql")))
        
        for sql_file in sql_files:
            print(f"Aplicando {os.path.basename(sql_file)}...")
            with open(sql_file, 'r', encoding='utf-8') as f:
                sql = f.read()
            try:
                cur.execute(sql)
                print(f"  OK: {os.path.basename(sql_file)}")
            except Exception as e:
                print(f"  Erro em {os.path.basename(sql_file)}: {e}")
        
        cur.close()
        conn.close()
        print("Migrações concluídas!")
    except Exception as e:
        print(f"Erro ao conectar: {e}")

if __name__ == "__main__":
    apply_migrations()
