import os
import subprocess


def dump_mysql_db(
    db_name, username, output_file, password=None, host="localhost", port=3306
):
    """
    Create a MySQL database dump using mysqldump.
    
    Args:
        db_name (str): Database name
        username (str): MySQL username
        output_file (str): Output dump file path
        password (str, optional): MySQL password
        host (str): MySQL host
        port (int): MySQL port
    """
    # Construct the mysqldump command
    dump_command = [
        "mysqldump",
        "--host=" + host,
        "--port=" + str(port),
        "--user=" + username,
        "--single-transaction",  # For InnoDB tables
        "--routines",           # Include stored procedures and functions
        "--triggers",           # Include triggers
        "--events",             # Include events
        "--result-file=" + output_file,
        db_name,
    ]
    
    # Set password via environment variable if provided
    env = os.environ.copy()
    if password:
        env["MYSQL_PWD"] = password

    try:
        # Execute the mysqldump command
        result = subprocess.run(
            dump_command, 
            check=True, 
            text=True, 
            capture_output=True,
            env=env
        )
        return True
    except subprocess.CalledProcessError as e:
        print(f"Error creating MySQL dump: {e}")
        return False
    except FileNotFoundError:
        print("mysqldump command not found. Please ensure MySQL client tools are installed.")
        return False