# Author: Thomas Krenc
#         tkrenc@caida.org
# Description: This code is to reproduce the results presented in
#         the paper "Coarse-grained Inference of BGP Community Intent"
#         at IMC'23

import sys
import numpy as np
import pandas as pd

from sklearn.metrics import classification_report
from sklearn.metrics import confusion_matrix
from sklearn.metrics import accuracy_score

class CommunityInference:

    def __init__(self):
        print("# __init__")

    def predict_default(self, df_nc, onoffratio=160, custpeerratio=5):
        print("# predict_default")

        df_nc['pred'] = 'action'

        df_nc.loc[df_nc['off']==0,'pred'] = 'info'
        df_nc.loc[(df_nc['off']>0) & (df_nc['onoffratio']>onoffratio),'pred'] = 'info' # ok

        # if never 'onpath' and 'alpha' not in asn-list (i.e., alpha could be ixp or merged ISP)
          #   mark as ixp
        df_nc.loc[ (df_nc['on']==0) & ~(df_nc.index.get_level_values(0).isin(self.df_asns['asn'].tolist())) ,'pred'] = 'ixp'


    def recalc_onoff(self, onoffratio, comm, clust):
        print("# recalc_onoff")

        self.predict_default(clust, onoffratio)

        # zip clusters and predictions
        preds = dict(zip(clust.index.get_level_values(2),clust['pred'].values))

        # apply prediction to each community using prediction of cluster
        comm['pred'] = comm['cluster'].apply(lambda x: preds[x])

        # remove records that are potentially IXPs or merged ISPs
        comm.drop(comm[comm['pred'] == 'ixp'].index, inplace=True)
        clust.drop(clust[clust['pred'] == 'ixp'].index, inplace=True)


    def infer_default(self, onoffratio=160):
        print("# infer_default")

        # use the full list of communities
        df = self.feat_augmented.copy()

        # restrict full list to ...
        df = self.get_regularcomm_feats(df)

        def myagg(x):

            res = {}

            res['on'] = x['on'].mean()
            res['off'] = x['off'].mean()
            res['count'] = len(x['comm'])

            y = pd.DataFrame(res, index=[0])

            return y

        clust = df.groupby(['alpha','cat','cluster']).apply(lambda g: myagg(g))

        if len(clust) == 0:
          print("[CommunityInference.py] warn: zero clusters. skipping inference");
          return [df, clust]

        clust['onoffratio'] = clust['on']/clust['off']

        self.recalc_onoff(onoffratio, df, clust)

        print(len(clust), "clusters used")

        prediction = df[df['cat']!=""]['pred']
        y_test = df[df['cat']!=""]['cat']

        print("confusion matrix:\n", confusion_matrix(y_test, prediction))
        print("accuracy score: ", accuracy_score(y_test, prediction))
        print(classification_report(y_test, prediction))

        return [df, clust]


    def augment_clusters(self, maxgap):
        print("# augment_clusters")

        def __cluster_by_gap(data, maxgap, alpha):
            '''Arrange data into groups where successive elements
               differ by no more than *maxgap*

                >>> cluster([1, 6, 9, 100, 102, 105, 109, 134, 139], maxgap=10)
                [[1, 6, 9], [100, 102, 105, 109], [134, 139]]

                >>> cluster([1, 6, 9, 99, 100, 102, 105, 134, 139, 141], maxgap=10)
                [[1, 6, 9], [99, 100, 102, 105], [134, 139, 141]]

            '''

            C = np.array([])

            data.sort()
            groups = [[data[0]]]
            _c = 0
            C = np.append(C, str(alpha)+"-"+str(_c))
            for x in data[1:]:
                if abs(x - groups[-1][-1]) <= maxgap:
                    groups[-1].append(x)
                    C = np.append(C, str(alpha)+"-"+str(_c))
                else:
                    groups.append([x])
                    _c = _c + 1
                    C = np.append(C, str(alpha)+"-"+str(_c))
            return C, groups

        df = self.feat_augmented

        # iterate over unique alpha values
        for alpha in sorted(np.unique(df['alpha'])):

            X = np.array(df[df['alpha']==alpha]['beta']).reshape(-1, 1)

            labels, groups = __cluster_by_gap(X, maxgap, alpha)

            df.loc[df['alpha']==alpha, 'cluster'] = labels

        self.feat_augmented = df

        print("# clustered")


    def augment_feats(self, cat_file):
        print("# augment_feats")

        # create a copy from raw dataframe
        data = self.feat_raw.copy()

        # extracts column separated fields
        data['alpha'] = data['comm'].apply(lambda x: x.split(":")[0]).astype(int)
        data['beta'] = data['comm'].apply(lambda x: x.split(":")[1]).astype(int)

        data = data.sort_values(by=['alpha','beta'], ascending=True)

        # is community a large community (rfc8092)?
        data['large'] = data['comm'].str.count(":")==2

        # is community a (IANA) public (as opposed private / reserved)?
        data['public'] = data['alpha'].apply(self.is_public)

        # augment level-1 category from ground truth (action and info)
        _comms = pd.read_csv(cat_file)
        print("# read comms: ", cat_file)
        cats = dict(zip(_comms['comm'], _comms['cat']))
        data['cat'] = data['comm'].apply(lambda x: cats[x] if x in cats else '')

        self.feat_augmented = data
        print("# augmented feats")

    # return labeled communities, i.e., w/ ground truth data
    def get_labeled_feats(self, data):
        print("# get_labeled_feats")

        return data[data['cat']!='']

    # return regular communities (rfc1997, as opposed to large rfc8092 communities)
    def get_regularcomm_feats(self, data):
        print("# get_regularcomm_feats")

        return data[data['large']==False]


    def load_asns(self, file):
        print("# load_asns")

        df = pd.read_csv(file, sep='@', names=['asn'])
        self.df_asns = df[~df['asn'].str.contains('{|}')].astype(int)

        print("# read asns: ", file)

    def load_feats(self, onoff):
        print("# load_feats")

        df = pd.read_csv(onoff, sep='|', names=['comm', 'type', 'num'])

        if len(df) == 0:
          print("[CommunityInference.py] warn: onoff metrics are empty. skipping")
          sys.exit()

        final = pd.pivot_table(df, values="num", index=["comm"], columns=["type"]).reset_index()

        # hack to deal with malformed beta values (routeviews collector)
        final = final[final.comm.apply(lambda x: x.split(":")[1].isnumeric())]

        self.feat_raw = final
        print("# read feats: ", onoff)

    # checks if alpha is a public ASN
    def is_public(self, alpha):
        return (int(alpha) >= 1 and int(alpha) <= 64495 and int(alpha) != 23456) \
            or (int(alpha) >= 131072 and int(alpha) <= 4199999999)
