import os
import subprocess


def dump_postgres_db(
    db_name, username, output_file, password=None, host="localhost", port=5432
):
    """
    Create a PostgreSQL database dump using pg_dump.
    
    Args:
        db_name (str): Database name
        username (str): PostgreSQL username
        output_file (str): Output dump file path
        password (str, optional): PostgreSQL password
        host (str): PostgreSQL host
        port (int): PostgreSQL port
        
    Returns:
        bool: True if successful, False otherwise
    """
    # Set environment variable for the password if provided
    if password:
        os.environ["PGPASSWORD"] = password

    # Construct the pg_dump command
    dump_command = [
        "pg_dump",
        "-h",
        host,
        "-p",
        str(port),
        "-U",
        username,
        "-F",
        "c",  # Custom format
        "-f",
        output_file,
        db_name,
    ]

    try:
        # Execute the pg_dump command
        result = subprocess.run(
            dump_command, check=True, text=True, capture_output=True
        )
        return True
    except subprocess.CalledProcessError as e:
        print(f"Error creating PostgreSQL dump: {e}")
        return False
    except FileNotFoundError:
        print("pg_dump command not found. Please ensure PostgreSQL client tools are installed.")
        return False
    finally:
        # Clean up the environment variable
        if password:
            del os.environ["PGPASSWORD"]
