# coding: utf-8
import logging

import yenv

from .base import StatfaceBaseCommand, yql_client

logger = logging.getLogger(__name__)


class Command(StatfaceBaseCommand):
    TASK_NAME = 'BatchResponseTimePercentileCounter'
    report = StatfaceBaseCommand.client.get_report('ExtData/idm/api/batch_time_percentile')
    query = """
-- idm_api_v1_batch_response_percentile
USE HAHN;
PRAGMA yson.DisableStrict;

$script=@@
from datetime import datetime
from pytz import timezone
import pytz

moscow = timezone('Europe/Moscow')

def date_formatter(ts):
    if ts:
        try:
            ts = int(float(ts))
            ts = ts - ts % 300
            return datetime.utcfromtimestamp(ts).replace(tzinfo=pytz.UTC).astimezone(moscow).strftime('%Y-%m-%d %H:%M:%S')
        except ValueError:
            return ts.split('T')[0]
    else:
        return ts
@@;

$date_formatter = Python::date_formatter(
    Callable<(String?)->String?>,
    $script
);

$user_email = ($fields) -> {{ return Yson::ConvertToString($fields.context.user.email); }};
$final_flag = ($fields) -> {{ return Yson::ConvertToInt64($fields.context.profiling.final); }};
$request_path = ($fields) -> {{ return Yson::ConvertToString($fields.context.request.path); }};
$execution_time = ($fields) -> {{ return Yson::ConvertToInt64($fields.context.execution_time); }};

SELECT 
    MEDIAN(execution_time) as median_,
    PERCENTILE(execution_time, 0.9) as percentile_90,
    PERCENTILE(execution_time, 0.95) as percentile_95,
    PERCENTILE(execution_time, 0.99) as percentile_99
FROM 
(
    SELECT $execution_time(fields) as execution_time

    FROM `home/logfeller/logs/qloud-runtime-log/stream/5min/{table_name}`

    WHERE
        qloud_project = "tools-access" AND
        qloud_application = "idm" AND
        qloud_environment = "{qloud_environment}" and
        $request_path(fields) = '/api/v1/batch/' AND
        $user_email(fields) = 'cauth-robot-rw@yandex-team.ru' AND
        $final_flag(fields) = 1
) 
        """

    def get_data_from_yt(self):
        current_time = self.get_current_time()
        full_query = self.query.format(
            table_name=current_time,
            qloud_environment=yenv.type
        )

        request = yql_client.query(full_query, syntax_version=1)
        request.run()
        return request

    def populate_data(self, request):
        result = []
        for raw_dict in super(Command, self).populate_data(None, request):
            if any(value for value in raw_dict.values()):
                raw_dict['fielddate'] = self.get_current_time()
            else:
                # если yt ничего не вернул, заполнить нулями
                raw_dict = self.get_initial_values()
            result.append(raw_dict)

        return result

    def get_initial_values(self):
        return {
            'median_': 0,
            'percentile_90': 0,
            'percentile_95': 0,
            'percentile_99': 0,
            'fielddate': self.get_current_time()
        }

    def idm_handle(self, *args, **kwargs):
        request = self.get_data_from_yt()
        result = self.populate_data(request)
        if not request.errors:
            self.upload_to_statface(result)

