from apscheduler.schedulers.asyncio import AsyncIOScheduler
import logging

scheduler = AsyncIOScheduler()
logger = logging.getLogger("infra-assistant")


def start_scheduler():
    scheduler.add_job(run, "interval", minutes=5)
    scheduler.start()
    logger.info("Scheduler started (interval=5min)")


async def run():
    # Imports SAFE (aucun crash au boot)
    try:
        from connectors.grafana import fetch_alerts
    except ImportError:
        logger.warning("Grafana connector not available")
        return

    try:
        from correlation.engine import correlate
    except ImportError:
        logger.warning("Correlation engine not available")
        return

    try:
        from llm.client import summarize
    except ImportError:
        summarize = None

    try:
        from notifications.logger import log_alert
        from notifications.mailer import send_mail
    except ImportError:
        logger.warning("Notification system not available")
        return

    # --- Pipeline ---
    alerts = await fetch_alerts()

    for alert in alerts:
        context = correlate(alert)

        if summarize:
            message = summarize(context)
        else:
            message = "Alert received but LLM unavailable"

        log_alert(message)
        send_mail(message)
