from urllib.parse import quote_plus
from sqlalchemy import create_engine
from sqlalchemy import create_engine, inspect, text

# Replace with your actual master DB credentials
# Example: postgresql://username:password@host:port/database

password = quote_plus("gQube#@96740")  # Encode special chars
master_engine = create_engine("postgresql://postgres:{password}@134.209.155.11:5432/greenqube_master_db")
print(engine.url)
master_inspector = inspect(master_engine)

def get_master_tables():
    """
    Returns a list of all tables in the master database.
    """
    return master_inspector.get_table_names()

def get_master_columns():
    """
    Returns a dictionary of table → list of column names.
    """
    return {
        table: [col['name'] for col in master_inspector.get_columns(table)]
        for table in get_master_tables()
    }

def fetch_master_data(table, limit=100):
    """
    Returns up to `limit` rows from the specified master table.
    """
    with master_engine.connect() as conn:
        result = conn.execute(text(f"SELECT * FROM {table} LIMIT {limit}"))
        return [dict(row) for row in result]

def get_master_mapping(table: str, key_col: str, value_col: str) -> dict:
    """
    Returns a dictionary mapping key_col → value_col from the given master table.
    Useful for enriching values in join_generator.py.
    """
    with master_engine.connect() as conn:
        result = conn.execute(text(f"SELECT {key_col}, {value_col} FROM {table}"))
        return {row[key_col]: row[value_col] for row in result}