from django.http import HttpResponse
from libs.es import health
from rank.models import Strategy
from libs.cache import redis_client
from doris.celery import debug_task
import json, traceback


def _check_es():
    error = {}
    es_ok = True
    try:
        res = health()
        if res['status'] == 'green':
            es_ok = True
        else:
            error = {
                "elasticsearch": res,
            }
            es_ok = False
    except:
        error = {
            "elasticsearch": traceback.format_exc()
        }
        es_ok = False

    return es_ok, error


def _check_mysql():
    error = {}
    mysql_ok = True
    try:
        item = Strategy.objects.last()
    except:
        mysql_ok = False
        error = {
            "mysql": traceback.format_exc()
        }
    return mysql_ok, error


def _check_redis():
    error = {}
    redis_ok = True
    try:
        redis_client.set("test", "test")
    except:
        redis_ok = False
        error = {
            "redis": traceback.format_exc()
        }
    return redis_ok, error


def _check_celery():
    error = {}
    celery_ok = True
    try:
        debug_task.delay()
    except:
        celery_ok = False
        error = {
            "celery": traceback.format_exc()
        }
    return celery_ok, error


def statuses(request):
    ok = True
    errors = {}
    resp = {
        'ok': ok,
        'errors': errors
    }
    # check es

    es_ok, error = _check_es()
    if not es_ok:
        errors.update(error)
    # check redis
    mysql_ok, error = _check_mysql()
    if not mysql_ok:
        errors.update(error)

    redis_ok, error = _check_redis()
    if not redis_ok:
        errors.update(error)

    celery_ok, error = _check_celery()
    if not celery_ok:
        errors.update(error)

    resp['ok'] = es_ok and mysql_ok and redis_ok and celery_ok
    return resp