"""Recording scheduled-job outcomes.

Wrap the body of any cron-triggered view in ``record_job`` and its result shows
up on the health panel. Never lets bookkeeping break the job itself.

    with record_job('fetch_emails', every_minutes=5) as job:
        ...
        job.detail = '3 new tickets'
"""
from contextlib import contextmanager

from django.utils import timezone


@contextmanager
def record_job(name, every_minutes=15):
    from core.models import JobRun

    class _Ctx:
        detail = ''

    ctx = _Ctx()
    started = timezone.now()
    try:
        yield ctx
    except Exception as exc:
        _write(name, JobRun.FAILED, started, every_minutes, str(exc)[:2000], ctx.detail)
        raise
    else:
        _write(name, JobRun.OK, started, every_minutes, '', ctx.detail)


def _write(name, status, started, every_minutes, error, detail):
    """Persist the outcome. Swallows its own errors on purpose — a failure to
    record must never turn a working job into a broken one."""
    try:
        from core.models import JobRun
        from django.db.models import F

        defaults = {
            'status': status,
            'last_run_at': started,
            'detail': (detail or '')[:500],
            'error': error,
            'expected_every_minutes': every_minutes,
        }
        if status == JobRun.OK:
            defaults['last_ok_at'] = timezone.now()

        job, created = JobRun.objects.get_or_create(name=name, defaults=defaults)
        if not created:
            for k, v in defaults.items():
                setattr(job, k, v)
            job.save()
        JobRun.objects.filter(pk=job.pk).update(
            run_count=F('run_count') + 1,
            fail_count=F('fail_count') + (0 if status == JobRun.OK else 1),
        )
    except Exception:
        pass
