import yenv

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


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

    SYNTAX_VERSION = 1

    LOG_TYPES = (DAY_LOG,)

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

    REPORT_PATH = {
        DAY_LOG: 'ExtData/idm/node_does_not_exist/daily'
    }

    YQL_QUERY = r"""
        -- idm_node_doest_not_exist_metric

        USE hahn;
        PRAGMA yson.DisableStrict;

        $log_name = ($fields) -> {{ return Yson::ConvertToString($fields.context.log_name); }};
        $system = ($fields) -> {{ return Yson::ConvertToString($fields.context.system); }};

        $parsed = (
            SELECT $system(fields) as system
              FROM `{log_path}{table_name}`
             WHERE
                   qloud_project = 'tools-access'
               AND qloud_application = 'idm'
               AND qloud_environment = '{qloud_environment}'
               AND $log_name(fields) = 'node_does_not_exist'
        );

        UPSERT INTO {stat_cluster}.`{report_path}`
             SELECT '{table_name}' as fielddate,
                    COALESCE(system, "__WRONG_VALUE__") as system,
                    COUNT(*) as count,
               FROM $parsed
           GROUP BY 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
