from sqlalchemy import create_engine, text
import os
from dotenv import load_dotenv

# .env-Datei laden
load_dotenv()

# Schritt 1: Verbindung zur MariaDB herstellen, OHNE eine bestimmte Datenbank
DATABASE_URL = f"mysql+pymysql://root:{os.getenv('DB_ROOT_PASSWORD')}@{os.getenv('DB_HOST')}:3306"

engine = create_engine(DATABASE_URL, isolation_level="AUTOCOMMIT", echo=True)

db_name = os.getenv("DB_NAME")
db_user = os.getenv("DB_USER")
db_password = os.getenv("DB_PASSWORD")

with engine.connect() as connection:
    # Datenbank erstellen
    connection.execute(
        text(f"CREATE DATABASE IF NOT EXISTS `{db_name}` CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci")
    )

    # Benutzer erstellen
    connection.execute(
        text(f"CREATE USER IF NOT EXISTS '{db_user}'@'%' IDENTIFIED BY '{db_password}'")
    )

    # Berechtigungen vergeben
    connection.execute(
        text(f"GRANT ALL PRIVILEGES ON `{db_name}`.* TO '{db_user}'@'%'")
    )

    # Berechtigungen neu laden
    connection.execute(text("FLUSH PRIVILEGES"))

print("✅ Datenbank und Benutzer erfolgreich erstellt.")
