import asyncio

from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware

from app.api.router import api_router
from app.core.config import get_settings
from app.services.fiscal_document_inbox_service import sync_all_ready_fiscal_document_inboxes


settings = get_settings()
app = FastAPI(title=settings.app_name, version="0.1.0")
_fiscal_inbox_task: asyncio.Task[None] | None = None

app.add_middleware(
    CORSMiddleware,
    allow_origins=settings.cors_origins_list,
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

app.include_router(api_router)


async def _fiscal_inbox_poll_loop() -> None:
    while True:
        try:
            await sync_all_ready_fiscal_document_inboxes()
        except Exception:
            pass
        await asyncio.sleep(max(30, settings.fiscal_document_inbox_poll_seconds))


@app.on_event("startup")
async def startup_background_tasks() -> None:
    global _fiscal_inbox_task
    if _fiscal_inbox_task is None or _fiscal_inbox_task.done():
        _fiscal_inbox_task = asyncio.create_task(_fiscal_inbox_poll_loop())


@app.on_event("shutdown")
async def shutdown_background_tasks() -> None:
    global _fiscal_inbox_task
    if _fiscal_inbox_task is not None:
        _fiscal_inbox_task.cancel()
        try:
            await _fiscal_inbox_task
        except asyncio.CancelledError:
            pass
        _fiscal_inbox_task = None
