# main.py
import os

from fastapi import FastAPI
import uvicorn

from prism.db.client import DbClient
from prism import ApiPrism

# --- 1. Configuration ---
# Load database credentials from the .env file
print("▶️  Loading configuration from .env file...")

# Construct the database URL from environment variables, using the defaults
# from your hub.py as fallbacks.
db_name = os.getenv("DB_NAME", "a_hub")
user = os.getenv("DB_OWNER_ADMIN", "a_hub_admin")
password = os.getenv("DB_OWNER_PWORD", "password")
host = os.getenv("DB_HOST", "localhost")
port = os.getenv("DB_PORT", "5432")

DATABASE_URL = f"postgresql://{user}:{password}@{host}:{port}/{db_name}"

if not all([db_name, user, password, host, port]):
    raise ValueError("One or more database environment variables are missing.")

# --- 2. Initialization ---
# Create the main FastAPI application instance
app = FastAPI(
    title=f"Prism-py: {db_name}",
    description="API automatically generated by the refactored prism-py library.",
    version="0.1.0-refactored",
)

# Initialize the database client using the constructed URL.
# The new DbClient is simpler and focuses only on connectivity.
print(f"🌍 Connecting to database '{db_name}' on {host}:{port}...")
db_client = DbClient(db_url=DATABASE_URL)
db_client.test_connection()  # Verify the connection is alive

# Initialize the main ApiPrism orchestrator.
# Note how we no longer create a `ModelManager` manually. ApiPrism now
# handles the introspection process internally using its `Introspector`.
api_prism = ApiPrism(db_client=db_client, app=app)


# --- 3. API Route Generation ---
# Define the list of schemas to process, taken directly from your hub.py
schemas = [
    "account",
    "auth",
    "agnostic",
    "infrastruct",
    "hr",
    "academic",
    "course_offer",
    "student",
    "library",
]
api_prism.generate_all_routes(schemas)


# --- 4. Server Startup ---
# Add a simple root endpoint for a basic health check.
@app.get("/")
def read_root():
    return {
        "message": "Prism-py is running!",
        "docs_url": "/docs",
        "active_schemas": schemas,
    }


# Use the ui module to print a nice welcome banner.
server_host = "127.0.0.1"
server_port = 8000
# ui.print_welcome(
#     project_name=f"Prism-py: {db_name}",
#     version="0.1.0-refactored",
#     host=server_host,
#     port=server_port
# )

# Standard Python entry point to run the server with Uvicorn.
if __name__ == "__main__":
    print(f"🚀 Starting server at http://{server_host}:{server_port}")
    print("   Press CTRL+C to stop.")
    uvicorn.run(app, host=server_host, port=server_port)
