from contextlib import asynccontextmanager

from fastapi import FastAPI

from app.api import health, monitor, wechat_personal
from app.clients.mci_server_client import MciServerClient
from app.config import settings
from app.repositories.event_store import event_store
from app.services.event_publisher import EventPublisher


@asynccontextmanager
async def lifespan(app: FastAPI):
    client = MciServerClient(settings.mci_server_url)
    publisher = EventPublisher(
        event_store,
        client,
        max_retry=settings.max_retry,
        base_delay_seconds=settings.base_retry_delay_seconds,
        interval_seconds=settings.event_publish_interval_seconds,
    )
    publisher.start()
    yield
    await publisher.stop()


app = FastAPI(title=settings.app_name, debug=settings.debug, lifespan=lifespan)

app.include_router(health.router)
app.include_router(wechat_personal.router)
app.include_router(monitor.router)


if __name__ == "__main__":
    import uvicorn
    uvicorn.run("app.main:app", host=settings.host, port=settings.port, reload=settings.debug)
