import logging

from apscheduler.triggers.interval import IntervalTrigger
from core.scheduler import scheduler
from nginxmon.fetcher import fetch_and_store, cleanup_old_logs
from nginxmon.detector import detect_threats

logger = logging.getLogger(__name__)

_FETCH_JOB = 'nginxmon_fetch'
_CLEANUP_JOB = 'nginxmon_cleanup'


def start_fetch_job(interval_seconds: int):
    scheduler.add_job(
        fetch_and_store,
        trigger=IntervalTrigger(seconds=interval_seconds),
        id=_FETCH_JOB,
        replace_existing=True,
        misfire_grace_time=60,
    )
    logger.info('nginxmon: scheduled fetch every %ds', interval_seconds)


def stop_fetch_job():
    if scheduler.get_job(_FETCH_JOB):
        scheduler.remove_job(_FETCH_JOB)


def schedule_profile(profile):
    job_id = f'nginxmon_detect_{profile.pk}'
    scheduler.add_job(
        detect_threats,
        trigger=IntervalTrigger(seconds=max(60, profile.alert_window_seconds)),
        id=job_id,
        args=[profile.pk],
        replace_existing=True,
        misfire_grace_time=120,
    )
    logger.info('nginxmon: scheduled detect for profile "%s"', profile.name)


def unschedule_profile(profile):
    job_id = f'nginxmon_detect_{profile.pk}'
    if scheduler.get_job(job_id):
        scheduler.remove_job(job_id)


def start_cleanup_job():
    if not scheduler.get_job(_CLEANUP_JOB):
        scheduler.add_job(
            cleanup_old_logs,
            trigger=IntervalTrigger(hours=24),
            id=_CLEANUP_JOB,
            replace_existing=True,
        )
