import logging import os import sys import traceback from contextlib import asynccontextmanager from apscheduler.schedulers.background import BackgroundScheduler from apscheduler.triggers.cron import CronTrigger from fastapi import FastAPI, Request from fastapi.middleware.cors import CORSMiddleware from fastapi.responses import JSONResponse from .core.config import settings as app_settings from .core.db import SessionLocal, engine, get_scheduler_db from .core.exceptions import CodedHTTPException, coded_http_exception_handler from .core.migrations import run_sqlite_migrations from .models import Base from .routers import ( ai_reports, assets, attachments, audit, auth, calibration, complaints, contracts, dashboard, demo_equipment, health, insurance, masters, notifications, pm, reports, search, settings, users, visits, warranties, ) from .services.alerts import run_alert_check from .services.settings_service import ensure_default_settings logging.basicConfig( format="%(asctime)s | %(levelname)s | %(name)s | %(message)s", level=logging.INFO, ) logger = logging.getLogger("xyz_ams") def _scheduled_alert_job() -> None: try: with get_scheduler_db() as db: res = run_alert_check(db) logger.info("Scheduled alert check finished: %s", res) except Exception: logger.exception("Scheduled alert check failed.") @asynccontextmanager async def lifespan(app: FastAPI): Base.metadata.create_all(bind=engine) run_sqlite_migrations(engine) with SessionLocal() as db: ensure_default_settings(db) db.commit() logger.info("Database tables created/verified.") if app_settings.SECRET_KEY in { "change-me-in-production-32-chars-min", "change-me-in-production-use-a-32-char-random-string", }: logging.warning( "SECURITY: SECRET_KEY is set to the insecure default. Set a strong SECRET_KEY env var before any non-local use." ) scheduler: BackgroundScheduler | None = None is_testing = bool(os.environ.get("PYTEST_CURRENT_TEST") or "pytest" in sys.modules) if not is_testing: _scheduled_alert_job() scheduler = BackgroundScheduler(timezone=app_settings.TIMEZONE) scheduler.add_job( _scheduled_alert_job, trigger=CronTrigger(hour=6, minute=0, timezone=app_settings.TIMEZONE), id="daily_alert_check", replace_existing=True, ) scheduler.start() logger.info("APScheduler daily alert check started (06:00 %s).", app_settings.TIMEZONE) logger.info("XYZ Hospital AMS started.") try: yield finally: if scheduler is not None: scheduler.shutdown(wait=False) logger.info("APScheduler stopped.") app = FastAPI( title="XYZ Hospital AMS", version="0.1.0", docs_url="/docs", lifespan=lifespan, ) app.add_middleware( CORSMiddleware, allow_origins=["http://localhost:5173", "http://127.0.0.1:5173"], allow_credentials=True, allow_methods=["*"], allow_headers=["*"], ) app.add_exception_handler(CodedHTTPException, coded_http_exception_handler) @app.exception_handler(Exception) async def global_exception_handler(request: Request, exc: Exception): logger.error(f"Unhandled exception: {traceback.format_exc()}") return JSONResponse( status_code=500, content={"detail": "An internal error occurred.", "code": "INTERNAL_ERROR"}, ) app.include_router(health.router, prefix="/api") app.include_router(auth.router, prefix="/api") app.include_router(settings.router, prefix="/api") app.include_router(masters.router, prefix="/api") app.include_router(users.router, prefix="/api") app.include_router(assets.router, prefix="/api") app.include_router(attachments.router, prefix="/api") app.include_router(complaints.router, prefix="/api") app.include_router(pm.router, prefix="/api") app.include_router(calibration.router, prefix="/api") app.include_router(contracts.router, prefix="/api") app.include_router(warranties.router, prefix="/api") app.include_router(insurance.router, prefix="/api") app.include_router(demo_equipment.router, prefix="/api") app.include_router(visits.router, prefix="/api") app.include_router(notifications.router, prefix="/api") app.include_router(dashboard.router, prefix="/api") app.include_router(reports.router, prefix="/api") app.include_router(ai_reports.router, prefix="/api") app.include_router(search.router, prefix="/api") app.include_router(audit.router, prefix="/api")