"""FastAPI entry point for the Village Simulation backend.""" import os import uvicorn from fastapi import FastAPI from fastapi.middleware.cors import CORSMiddleware from fastapi.responses import RedirectResponse from fastapi.staticfiles import StaticFiles from backend.api.routes import router from backend.core.engine import get_engine # Path to web frontend WEB_FRONTEND_PATH = os.path.join(os.path.dirname(os.path.dirname(__file__)), "web_frontend") # Create FastAPI app app = FastAPI( title="Village Simulation API", description="API for the Village Economy Simulation", version="1.0.0", docs_url="/docs", redoc_url="/redoc", ) # Add CORS middleware for frontend access app.add_middleware( CORSMiddleware, allow_origins=["*"], # In production, specify actual origins allow_credentials=True, allow_methods=["*"], allow_headers=["*"], ) # Include API routes app.include_router(router, prefix="/api", tags=["simulation"]) @app.on_event("startup") async def startup_event(): """Initialize the simulation on startup with config.json values.""" from backend.config import get_config config = get_config() engine = get_engine() # Use reset() which automatically loads config values engine.reset() print(f"Village Simulation initialized with {config.world.initial_agents} agents") @app.get("/", tags=["root"]) def root(): """Root endpoint - redirect to web frontend.""" return RedirectResponse(url="/web/") @app.get("/health", tags=["health"]) def health_check(): """Health check endpoint.""" engine = get_engine() return { "status": "healthy", "simulation_running": engine.is_running, "agents_alive": len(engine.world.get_living_agents()), } # ============== Web Frontend ============== @app.get("/web", include_in_schema=False) def redirect_to_web_frontend(): """Redirect /web to /web/ for static file serving.""" return RedirectResponse(url="/web/") # Mount static files for web frontend (access at http://localhost:8000/web/) if os.path.exists(WEB_FRONTEND_PATH): app.mount("/web", StaticFiles(directory=WEB_FRONTEND_PATH, html=True), name="web_frontend") else: print(f"Warning: Web frontend not found at {WEB_FRONTEND_PATH}") def main(): """Run the server.""" uvicorn.run( "backend.main:app", host="0.0.0.0", port=8000, reload=True, ) if __name__ == "__main__": main()