villsim/backend/main.py
Снесарев Максим 67dc007283 [new] web-based frontend
2026-01-19 19:44:38 +03:00

93 lines
2.3 KiB
Python

"""FastAPI entry point for the Village Simulation backend."""
import os
import uvicorn
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
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 with API information."""
return {
"name": "Village Simulation API",
"version": "1.0.0",
"docs": "/docs",
"web_frontend": "/web/",
"status": "running",
}
@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 Static Files ==============
# 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")
def main():
"""Run the server."""
uvicorn.run(
"backend.main:app",
host="0.0.0.0",
port=8000,
reload=True,
)
if __name__ == "__main__":
main()