# examples/main_tester.py
import os
import uvicorn
from fastapi import FastAPI
from prism.db.client import DbClient
from prism.prism import ApiPrism

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 required database environment variables are missing (DB_NAME, DB_USER, DB_PASSWORD, DB_HOST, DB_PORT)."
    )

app = FastAPI(
    title=f"Prism API: {db_name}",
    description="API automatically generated by the prism-py library.",
    version="0.2.0",
)

db_client = DbClient(db_url=DATABASE_URL)
db_client.log_connection_stats()  # Log detailed connection info to the console.

schemas_to_generate = [
    "account",
    "auth",
    "agnostic",
    "infrastruct",
    "hr",
    "academic",
    "course_offer",
    "student",
    "library",
]

api_prism = ApiPrism(
    db_client=db_client,
    app=app,
    schemas=schemas_to_generate,  # If this is omitted, all user schemas are used.
)

api_prism.gen_all_routes()

# api_prism.gen_metadata_routes()  # Generate /dt/* routes
# api_prism.gen_health_routes()  # Generate /health/* routes
# api_prism.gen_table_routes()  # Generate CRUD+ routes for all tables
# api_prism.gen_view_routes()  # Generate read-only routes for all views
# api_prism.gen_fn_routes()  # Generate routes for all functions
# api_prism.gen_proc_routes()  # Generate routes for all procedures
# api_prism.gen_trig_routes()  # Acknowledges triggers in the logs


api_prism.cache.log_stats()  # Log cache statistics to the console.
api_prism.print_welcome_message(host="127.0.0.1", port=8000)

# Standard Python entry point to run the server with Uvicorn.
if __name__ == "__main__":
    uvicorn.run(
        "examples.main_tester:app",  # Use the full path for robust reloading
        host="127.0.0.1",
        port=8000,
        reload=True,  # `reload=True` is great for development. Set to `False` for production.
    )
