import logging

from django.http import JsonResponse
from django.conf import settings

from staff.lib import requests
from staff.lib.decorators import available_by_tvm
from staff.lib.tvm2 import get_user_ticket
from staff.lib import tvm2


logger = logging.getLogger(__name__)
url = f"https://{settings.STAFFBACK_HOST}/oauth/check_invalid_robot_oauth_tokens/"


def get_invalid_robot_oauth_tokens():
    tokens = [
        settings.ROBOT_STAFF_OAUTH_TOKEN,
        settings.ROBOT_STAFF_PUNCHER_OAUTH_TOKEN,
        settings.ROBOT_STAFF_OK_OAUTH_TOKEN,
    ]
    invalid_tokens = []
    for token in tokens:
        ticket = get_user_ticket(oauth_token=token)
        if not ticket:
            invalid_tokens.append(token)
    return invalid_tokens


@available_by_tvm(['staff'])
def check_invalid_robot_oauth_tokens(request):
    invalid_tokens = get_invalid_robot_oauth_tokens()

    if invalid_tokens:
        return JsonResponse(data={"invalid_tokens": invalid_tokens})

    return JsonResponse(data={})


def monitor_check_invalid_robot_oauth_tokens():
    tvm_ticket = tvm2.get_tvm_ticket_by_deploy('staff')

    response = requests.get(
        url,
        headers={tvm2.TVM_SERVICE_TICKET_HEADER: tvm_ticket},
        timeout=30,
    )

    if response.status_code != 200:
        logger.error(f'Staff-back {response.text}')
        return
    return response.json()
