import re


def detect_script_vars(script_file, var_lst):
    """Detects from the input script file (script_file) which of given variables (var_lst) are demanded.

    Arguments
    ---------
    script_file : path
        Path of the script file needing the hyperparameters.
    var_lst : list
        list of the variables declared in the yaml file.

    Returns
    -------
    detected_var: list
        list of the variables detected in the script file.
    """
    detected_var = []
    with open(script_file) as f:
        for line in f:
            for var in var_lst:
                # The pattern can be ["key"] or ".key"
                if '["' + var + '"]' in line:
                    if var not in detected_var:
                        detected_var.append(var)
                        continue  # no need to go through the other cases for this var
                # case: hparams[f"{dataset}_annotation"] - only that structure at the moment
                re_match = re.search(r"\[f.\{.*\}(.*).\]", line)
                if re_match is not None:
                    if re_match.group(1) in var:
                        print(
                            "\t\tAlert: potential inconsistency %s maybe used in %s (or not)."
                            % (var, re_match.group(0))
                        )
                        if var not in detected_var:
                            detected_var.append(var)
                            continue
                if "." + var in line:
                    if var not in detected_var:
                        detected_var.append(var)
                        continue
                # case: getattr(self.hparams, "waveform_target", False):
                if 'attr(self.hparams, "' + var + '"' in line:
                    if var not in detected_var:
                        detected_var.append(var)
                        continue
                # case: tea_enc_list.append(hparams['tea{}_enc'])
                re_var = re.search(r"\[.(.*){}(.*).\]", line)
                if re_var is not None:
                    re_var_pattern = re_var.group(1) + ".*" + re_var.group(2)
                    re_pattern = re.search(re_var_pattern, var)
                    if re_pattern is not None:
                        if re_pattern.group() == var:
                            detected_var.append(var)
                            continue
    return detected_var