import yenv

from idm.metrics.management.base_api_response_percentile import MetricBaseCommand, MINUTE_LOG, DAY_LOG


class Command(MetricBaseCommand):
    """
    Команда считает персентили времени ответа и количество запросов с разбивкой по системам
    Считает по логам, в которых есть поле response._additional_fields.system
    """
    help = """Считает и загружает в статфейс статистику по времени ответа ручек с разбивкой по системам"""

    SYNTAX_VERSION = 1

    LOG_PATH = {
        MINUTE_LOG: 'home/logfeller/logs/qloud-runtime-log/stream/5min/',
        DAY_LOG: 'home/logfeller/logs/qloud-runtime-log/1d/',
    }

    REPORT_PATH = {
        MINUTE_LOG: 'ExtData/idm/api/idm_api_response_time_by_systems_5min/minutely',
        DAY_LOG: 'ExtData/idm/api/idm_api_response_time_by_systems_day/daily',
    }

    YQL_QUERY = r"""
        -- idm_api_responce_percentile_by_systems
        USE hahn;
        PRAGMA yson.DisableStrict;
    
        $path_match = Re2::Match("^/api/[\\w,\\-]+/[\\w,\\-]+(/.*)$");
        $capture = Pire::Capture("(/api/[\\w,\\-,\\d]+/[\\w,\\-,\\d]+/).*");
        
        $system = ($fields) -> {{ return Yson::ConvertToString($fields.context.request._additional_fields.system); }};
        $final_flag = ($fields) -> {{ return Yson::ConvertToInt64($fields.context.profiling.final); }};
        $status_code = ($fields) -> {{ return Yson::ConvertToInt64($fields.context.request.status_code); }};
        $path = ($fields) -> {{ return Yson::ConvertToString($fields.context.request.path); }};
        $method = ($fields) -> {{ return Yson::ConvertToString($fields.context.request.method); }};
        $execution_time = ($fields) -> {{ return Yson::ConvertToDouble($fields.context.execution_time); }};

        UPSERT INTO {stat_cluster}.`{report_path}`
            SELECT  '{table_name}' as fielddate,
                    http_method,
                    request_path,
                    system,
                    COUNT(*) as requests_count,
                    PERCENTILE(execution_time, 0.90) as percentile_90,
                    PERCENTILE(execution_time, 0.95) as percentile_95,
                    PERCENTILE(execution_time, 0.99) as percentile_99
               FROM (
                    -- COALESCE для конверитирования String? -> String 
                    SELECT COALESCE($capture($path(fields)), "") as request_path,
                           $execution_time(fields) as execution_time,
                           COALESCE($method(fields), "") as http_method,
                           COALESCE($system(fields), "") as system
                      FROM `{log_path}{table_name}`
                     WHERE qloud_project = 'tools-access'
                       AND qloud_application = 'idm'
                       AND qloud_environment = '{qloud_environment}'
                       AND $path_match($path(fields))
                       AND $capture($path(fields)) is NOT NULL
                       AND $status_code(fields) < 300
                       AND $system(fields) is NOT NULL
                       AND $final_flag(fields) = 1
               )
           GROUP BY http_method, request_path, system;
    """

    def get_yql_query(self, log_type, table_name):
        qloud_environment = yenv.type

        full_query = self.YQL_QUERY.format(
            table_name=table_name,
            qloud_environment=qloud_environment,
            stat_cluster=self.STAT_CLUSTERS[qloud_environment],
            report_path=self.REPORT_PATH[log_type],
            log_path=self.LOG_PATH[log_type],
        )
        return full_query
