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

# ==============================================================================
#  Prism-py: Main Example & Test Harness
# ==============================================================================
# This script serves as a comprehensive example of how to use the prism-py
# library. It demonstrates:
#   1. Loading database configuration securely from environment variables.
#   2. Initializing the core `DbClient` and `ApiPrism` components.
#   3. Generating API routes either all at once or in a modular, piece-by-piece fashion.
# ==============================================================================

# --- 1. Configuration ---
# Load database credentials from environment variables with sensible defaults
# for local development. This is a best practice for application configuration.
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")

# Construct the full database URL. DbClient uses this single string for configuration.
DATABASE_URL = f"postgresql://{user}:{password}@{host}:{port}/{db_name}"

# Fail fast if essential configuration is missing.
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)."
    )

# --- 2. Initialization ---
# Create the main FastAPI application instance.
# This object will be populated with routes by ApiPrism.
app = FastAPI(
    title=f"Prism API: {db_name}",
    description="API automatically generated by the prism-py library.",
    version="0.2.0",
)

# Initialize the database client. This object manages the connection pool.
db_client = DbClient(db_url=DATABASE_URL)
db_client.log_connection_stats()  # Log detailed connection info to the console.

# --- 3. API Generation ---

# Define the list of database schemas to expose through the API.
# If you leave this list empty, ApiPrism will discover and use ALL schemas.
# Providing a specific list is useful for security and focus.
schemas_to_generate = [
    "account",
    "auth",
    "agnostic",
    "infrastruct",
    "hr",
    "academic",
    "course_offer",
    "student",
    "library",
]

# Initialize the main ApiPrism orchestrator.
# It takes the db_client and the FastAPI app instance.
# You can optionally pass the list of schemas to process.
api_prism = ApiPrism(
    db_client=db_client,
    app=app,
    schemas=schemas_to_generate,  # If this is omitted, all user schemas are used.
)

# --- Option A: Generate all routes with a single command ---
# This is the simplest and recommended way to get started.
# It calls all the individual `gen_*_routes` methods in the correct order.
# api_prism.gen_all_routes()

# --- Option B: Generate routes modularly ---
# This approach gives you granular control. Each method is self-contained
# and can be called independently without causing errors.
# Introspection is run automatically on the first call.
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

# --- 4. Server Startup ---
# You can add your own custom endpoints to the app as well.

# Define server host and port.
server_host = "127.0.0.1"
server_port = 8000

api_prism.cache.log_stats()  # Log cache statistics to the console.
# Display the final welcome message with clickable links to the API docs.
api_prism.print_welcome_message(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(
        "examples.main_tester:app",  # Use the full path for robust reloading
        host=server_host,
        port=server_port,
        reload=True,  # `reload=True` is great for development. Set to `False` for production.
    )
