import re


def gapV(ig_dict, repo_dict):
    """
    Insert gaps into V region and update alignment information

    Arguments:
      ig_dict : Dictionary of parsed IgBlast output
      repo_dict : Dictionary of IMGT gapped germline sequences

    Returns:
      dict : Updated with SEQUENCE_IMGT, V_GERM_START_IMGT, and V_GERM_LENGTH_IMGT fields
    """

    seq_imgt = '.' * (int(ig_dict['V_GERM_START_VDJ']) - 1) + ig_dict['SEQUENCE_VDJ']
    #print("seq_imgt before gapping in gapV()", seq_imgt, file = sys.stderr)
    # present before gapping
    # Find gapped germline V segment
    vkey = ig_dict['V_ALLELE']
    #print("keys in repo_dict:", repo_dict.keys(), file=sys.stderr)
    #print("vkey of interest:", vkey, file=sys.stderr)
    if vkey in repo_dict:
        vgap = repo_dict[vkey]
        #print("vgap present?", vgap, file=sys.stderr)
        # Iterate over gaps in the germline segment
        gaps = re.finditer(r'\.', vgap)
        #print("vgap present?", gaps, file=sys.stderr)
        gapcount = int(ig_dict['V_GERM_START_VDJ']) - 1
        #print("gapcount present?", gapcount, file=sys.stderr)
        for gap in gaps:
            i = gap.start()
            # Break if gap begins after V region
            if i >= ig_dict['V_GERM_LENGTH_VDJ'] + gapcount:
                break
            # Insert gap into IMGT sequence
            seq_imgt = seq_imgt[:i] + '.' + seq_imgt[i:]
            # Update gap counter
            gapcount += 1
        #print("seq_imgt after gapping", seq_imgt, file=sys.stderr)
        ig_dict['SEQUENCE_IMGT'] = seq_imgt
        # Update IMGT positioning information for V
        ig_dict['V_GERM_START_IMGT'] = 1
        ig_dict['V_GERM_LENGTH_IMGT'] = ig_dict['V_GERM_LENGTH_VDJ'] + gapcount

    # print("seq_imgt keys() check after gapping in Vgap()", ig_dict.keys(), file=sys.stderr)
    return ig_dict