import os
from sqlalchemy import create_engine, MetaData, text
import pandas as pd

# Defaulting to the dummy SQLite DB forged in Phase 10
DEFAULT_DB_URI = f"sqlite:///{os.path.join(os.path.dirname(__file__), 'enterprise_data.db')}"

def reflect_database_schema(db_uri: str = DEFAULT_DB_URI) -> str:
    """Reflects the database and returns a string representation of all tables and columns."""
    try:
        engine = create_engine(db_uri)
        metadata = MetaData()
        metadata.reflect(bind=engine)
        
        schema_info = ["Database Schema:"]
        for table in metadata.tables.values():
            schema_info.append(f"\nTable: {table.name}")
            for column in table.c:
                schema_info.append(f"  - {column.name} ({column.type})")
                
        return "\n".join(schema_info)
    except Exception as e:
        return f"Error reflecting schema: {e}"

def query_database(sql_query: str, db_uri: str = DEFAULT_DB_URI) -> str:
    """Executes a READ-ONLY SQL query against the database and returns the results as a Markdown table."""
    try:
        # Basic SQL injection mitigation for Swarm agents (Enforcing READ-ONLY)
        upper_query = sql_query.upper()
        if any(keyword in upper_query for keyword in ["INSERT", "UPDATE", "DELETE", "DROP", "ALTER", "CREATE"]):
            return "ERROR: Agent is restricted to READ-ONLY SELECT queries."
            
        engine = create_engine(db_uri)
        with engine.connect() as connection:
            df = pd.read_sql(text(sql_query), connection)
            
        if df.empty:
            return "Query executed successfully. Zero rows returned."
            
        return df.to_markdown(index=False)
    except Exception as e:
        return f"Database query failed: {e}\nEnsure your SQL syntax is correct for the target dialect."
