#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Script that fixes hanging open jobs.
Dirty hack for fixing problem described in YANDEXTANK-436
"""

import sys
import socket
from settings import ENV_TYPE


if ENV_TYPE == 'production' and not 'vla' in socket.gethostname().split('.'):
    sys.stderr.write('In production the job closing hanging jobs works only on the VLA instance')
    sys.exit(0)

import time
from datetime import datetime, timedelta
from django.core.management.base import BaseCommand
from django.http import HttpRequest, QueryDict
from django.contrib.auth.models import User

from api.views.jobclose import JobClose
from common.models import Job
from common.util.clients import ClickhouseClient


class Command(BaseCommand):
    help = 'Close broken jobs'

    def handle(self, *args, **options):
        hour_ago = datetime.now() - timedelta(0, 3600, 0)
        online_jobs = Job.objects.filter(td=None, fd__lt=hour_ago).exclude(status='queued')
        self.stdout.write('{} [fix hanging jobs] Found {} hanging jobs.\n'.format(datetime.now(), online_jobs.count()))

        for job in online_jobs:
            try:
                ch_client = ClickhouseClient()
                self.stdout.write('{} [fix hanging jobs] Trying to find last second for job {}...\n'.format(
                    datetime.now(), job.n)
                )
                latest_sec = ch_client.select('''
                    select toUInt32(max(time))
                    from loaddb.rt_microsecond_details_buffer
                    where job_id={job}
                    and job_date=toDate({job_date})
                    ''', query_params=job.basic_query_params)
                if latest_sec and latest_sec[0][0] < time.mktime(hour_ago.timetuple()) or not latest_sec:
                    self.stdout.write('{} [fix hanging jobs] Closing job {}\n'.format(datetime.now(), job.n))
                    request = HttpRequest()
                    request.method = 'get'
                    request.GET = QueryDict('exitcode=100')
                    user_lunapark = User.objects.get(username='lunapark')
                    user_lunapark.login = 'lunapark'
                    request.yauser = user_lunapark
                    riper = JobClose()
                    riper.get(request, job)
                    self.stdout.write('{} [fix hanging jobs] Job {} closed.\n'.format(datetime.now(), job.n))
            except Exception:
                sys.stderr.write('{} [fix hanging jobs] FAILED TO CLOSE JOB {}'.format(datetime.now(), job.n))
