#!/opt/edge/venv/bin/python3.11
import ujson
import sys

from edge.support import fs
from edge.webserver.sysconf.dgmod import dg
from edge.webserver.sysconf.dgstats.blobstore import BsDgstats


def load_sc_metrics(term_pid):
    """
    :type term_pid: int
    :rtype: dict
    """
    sc_dgmod = dg.DgMod(dg.EDGE_TYPE_SPEEDCONTROL, str(10 * term_pid))
    sc_dgconf = sc_dgmod.load_main_conf()

    sc_stat_path = sc_dgconf['services']['stat']['path']
    return fs.load_json3(sc_stat_path)


def _main():
    metric = sys.argv[1]
    channel = sys.argv[2]
    origin = int(sys.argv[3])

    metric_path = metric.split('.')

    if metric_path[0] == 'cache':
        value = BsDgstats.get_cache_metric_64k(channel, metric_path[1])
        if value is not None:
            print(value)
            sys.exit(0)

    elif metric_path[0] == 'arch-session-count':
        count = BsDgstats.get_connections()
        if count is not None:
            print(count)
            sys.exit(0)
        else:
            sys.exit(0)

    elif metric_path[0] == 'cache-session-count':
        count = BsDgstats.get_connections(str(origin))
        if count is not None:
            print(count)
            sys.exit(0)
        else:
            sys.exit(0)

    elif metric_path[0] == 'write':
        sc_metrics = load_sc_metrics(origin)
        print(sc_metrics['bs'][str(channel)][metric_path[1]])

    else:
        print('Parameter not supported')


if __name__ == '__main__':
    _main()
