import yenv

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


class Command(MetricBaseCommand):
    help = """Считает и загружает в статфейс статистику по статусам ответов ручек"""

    SYNTAX_VERSION = 1

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

    REPORT_PATH = {
        MINUTE_LOG: 'ExtData/idm/api/idm_api_status_counts_5min/minutely',
        DAY_LOG: 'ExtData/idm/api/idm_api_status_counts_day/daily',
    }

    YQL_QUERY = r"""
        -- idm_api_status_counts
        USE hahn;
        
        $path_match = Re2::Match("^/api/[\\w,\\-]+/[\\w,\\-]+(/\\?.*|/)$");
        $capture = Pire::Capture("(/api/[\\w,\\-,\\d]+/[\\w,\\-,\\d]+/).*");
        $details_path_match = Re2::Match("^/api/(v[\\d]+|b2b|frontend)/((roles|approverequests)/\\d+/?$|rolenodes/([\\d,\\w,\\-]+/)+)");
        $details_capture = Pire::Capture("^(/api/(v[\\d]+|b2b|frontend)/(roles|approverequests|rolenodes)/)");
        $first_status_digit = Pire::Capture("^(2|4|5)");
        
        $request_records = (
                    SELECT COALESCE($capture(request), "") as request_path,
                           COALESCE(nginx_request_method, "") as http_method,
                           COALESCE(status, "") as status_raw,
                           COALESCE($first_status_digit(status) || "xx", "") as status_pattern
                      FROM `{log_path}{table_name}`
                     WHERE qloud_project = 'tools-access'
                       AND qloud_application = 'idm'
                       AND qloud_environment = '{qloud_environment}'
                       AND $path_match(request)
                       AND $capture(request) is NOT NULL
                     UNION ALL
                    -- details
                    SELECT COALESCE($details_capture(request) || "<id>", "") as request_path,
                           COALESCE(nginx_request_method, "") as http_method,
                           COALESCE(status, "") as status_raw,
                           COALESCE($first_status_digit(status) || "xx", "") as status_pattern
                      FROM `{log_path}{table_name}`
                     WHERE qloud_project = 'tools-access'
                       AND qloud_application = 'idm'
                       AND qloud_environment = '{qloud_environment}'
                       AND $details_path_match(request)
        );
        
        UPSERT INTO {stat_cluster}.`{report_path}`
            SELECT  '{table_name}' as fielddate,
                    http_method,
                    request_path,
                    status_raw as status,
                    COUNT(*) as responses_count
               FROM $request_records
           GROUP BY http_method, request_path, status_raw
           UNION ALL
            SELECT  '{table_name}' as fielddate,
                    http_method,
                    request_path,
                    status_pattern as status,
                    COUNT(*) as responses_count
               FROM $request_records
           GROUP BY http_method, request_path, status_pattern
           UNION ALL
            SELECT  '{table_name}' as fielddate,
                    http_method,
                    request_path,
                    "5xx part" as status,
                    (
                          CAST(COUNT_IF(status_pattern == "5xx") AS Float) / 
                          (
                              COUNT_IF(status_pattern == "2xx") +
                              COUNT_IF(status_pattern == "4xx") +
                              COUNT_IF(status_pattern == "5xx")
                          )
                      ) as responses_count
               FROM $request_records
           GROUP BY http_method, request_path
    ;
    """
    
    SKIP_IN_TESTING = True

    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
