import sys

# BMv2 specific paths
BMV2_TOOLS_PATH = "/home/ubuntu/bmv2-remote-attestation/tools"  # CLI tools
BMV2_TARGET_PATH = "/home/ubuntu/bmv2-remote-attestation/targets/simple_switch"  # Target

class BMV2Controller:
    def __init__(self, ip, port) -> None:
        """Initializes the BMV2 switch CP APIs"""
        # Import the bmv2 CP packages
        sys.path.append(BMV2_TOOLS_PATH)
        sys.path.append(BMV2_TARGET_PATH)
        ####### Bmv2 IMPORTS #######
        import runtime_CLI

        # from sswitch_runtime import SimpleSwitch
        from sswitch_CLI import SimpleSwitchAPI

        ############################
        print("Initializing bmv2 CLI APIs")
        pre = runtime_CLI.PreType.SimplePreLAG
        services = runtime_CLI.RuntimeAPI.get_thrift_services(pre)
        services.extend(SimpleSwitchAPI.get_thrift_services())
        standard_client, mc_client, sswitch_client = runtime_CLI.thrift_connect(
            ip, port, services
        )
        runtime_CLI.load_json_config(standard_client)
        self.ssapi = SimpleSwitchAPI(pre, standard_client, mc_client, sswitch_client)

    def read_register(self, reg_name: str):
        try:
            return self.ssapi.client.bm_register_read_all(0, reg_name)
        except Exception as e:
            print(f"[ERROR] Error reading register ({reg_name})..exiting", e)
            sys.exit()

    def reset_register(self, reg_name: str):
        try:
            return self.ssapi.client.bm_register_reset(0, reg_name)
        except Exception:
            print("[ERROR] Error reseting register..exiting")
            sys.exit()

    def get_switch_info(self):
        # json_cfg = self.ssapi.client.bm_get_config() # Getting the config from the switch
        info = self.ssapi.client.bm_mgmt_get_info()
        return info.thrift_port

    def read_counter(self, counter_name, index):
        return_val = self.ssapi.client.bm_counter_read(0, counter_name, index)
        return return_val
