"""A background-job worker on its own, without the API:

    python -m app.worker

Runs queued jobs (app/core/jobs.py) and the scheduler (app/core/scheduler.py)
— what every API process also does unless RUN_JOBS=false. Run as many as the
work needs; they share the queue safely.
"""

import asyncio
import signal

from app.core import platform_settings
from app.core.database import AsyncSessionLocal
from app.core.jobs import run_worker
from app.core.observability import configure_logging
from app.core.scheduler import scheduler_loop


async def main() -> None:
    stop = asyncio.Event()
    loop = asyncio.get_running_loop()
    for sig in (signal.SIGINT, signal.SIGTERM):
        try:
            loop.add_signal_handler(sig, stop.set)
        except NotImplementedError:  # Windows: Ctrl+C still raises KeyboardInterrupt
            pass
    # The Super Admin's overrides of .env (app/core/platform_settings.py).
    async with AsyncSessionLocal() as db:
        await platform_settings.load(db)
    tasks = [asyncio.create_task(run_worker()), asyncio.create_task(scheduler_loop()), asyncio.create_task(platform_settings.refresh_loop())]
    try:
        await stop.wait()
    finally:
        for task in tasks:
            task.cancel()
        await asyncio.gather(*tasks, return_exceptions=True)


if __name__ == "__main__":
    configure_logging()
    try:
        asyncio.run(main())
    except KeyboardInterrupt:
        pass
