from copy import deepcopy
import numpy as np

import AvenirCommon.Util as acu

import SpectrumCommon.Const.PJ.PJNTags as pjmvt
import SpectrumCommon.Const.GB.GBConst as gbc

import SpectrumCommon.Const.IC.ICConst as icc
import SpectrumCommon.Const.IC.ICConstLink as iccl
import SpectrumCommon.Const.IC.ICTags as icmvt
import SpectrumCommon.Const.IC.ICModVarFields as icmvf
import SpectrumCommon.Const.IC.IC_TI_InterventionIDs as ictii
import SpectrumCommon.Const.IC.ICInterventionIDs as icii
import SpectrumCommon.Modvars.IC.ICModVarUtil as icmvu
import SpectrumCommon.Util.IC.ICUtilLink as icul

import SpectrumCommon.Const.IH.IHTags as ihmvt


# Notes:
#
#   1. The only tangible purpose of versions on MVs is to be able to update them appropriately for existing projections so those projections can run with the
#      current codebase. The only code that ever checks MV versions is in the XXUpdateModvars file. If you just added a new field, you could just check and see if
#      the field is in the MV and add it if it's not without changing the version on the MV. Similarly, if you added a new dimension, you could just extend the
#      dimension of a MV without creating a new version. Changing the version number of a MV does gives us more of a history to follow, but doesn't do more
#      for us programmatically. Also, if you change the version of a MV, all clients using that MV need to update their code to use the latest MV.
#      Changing the version of a MV is only really useful if the MV undergoes a major structural change that would make it difficult to
#      manipulate the existing version of that MV otherwise, or if we would like to apply a correction to all previous versions of a MV.
#
#   2. You cannot base logic on whether a current MV tag exists in the code below.  It will always exist, because before this gets called, all missing MVs
#      will get added to the projection.
#
#   3. To trigger this, create a projection, say on the client, save, and grab it's projection ID (in Chrome, F12 --> Application --> session storage).
#      Change GB_PM_Version in GBConst or UpdateModvars will get skipped.  Add proj ID to Postman environment. Call Login, then GetModvars to get the library ID and put that
#      into the Postman environment. Then call OpenProjection. Make sure to leave the projection on the client open  while doing this because the proj ID changes when
#      you open/close. Then call SaveProjection. You should now be able to call Calculate and see the modified MV there where it's used. Don't forget to change
#      the version number back after you finish testing and trash the test projection.
#
def IC_UpdateModvars(projection, created_projection):

    # Interventions

    # Previous versions of this updater seem to have left multiple versions of the intervention records (at which point there was just version 1 and 2), so
    # delete all but the most recent one if there is more than one.
    if (IC_INTERV_RECORDS_TAG_V1 in projection) and (IC_INTERV_RECORDS_TAG_V2 in projection):
        del projection[IC_INTERV_RECORDS_TAG_V1]

    if IC_INTERV_RECORDS_TAG_V1 in projection:
        _convert_interv_records_1(projection, IC_INTERV_RECORDS_TAG_V1)
        _convert_interv_records_2(projection, icmvt.IC_INTERV_RECORDS_TAG)
        _convert_interv_records_3(projection, icmvt.IC_INTERV_RECORDS_TAG)

    elif IC_INTERV_RECORDS_TAG_V2 in projection:
        _convert_interv_records_2(projection, IC_INTERV_RECORDS_TAG_V2)
        _convert_interv_records_3(projection, icmvt.IC_INTERV_RECORDS_TAG)

    elif IC_INTERV_RECORDS_TAG_V3 in projection:
        _convert_interv_records_3(projection, IC_INTERV_RECORDS_TAG_V3)

    if (projection[pjmvt.GB_IHTOnTag]) and (gbc.GB_CS in projection[pjmvt.PJN_ModulesTag]):
        # Added 2/14/2025 IHT now shows all LiST interventions except the FamPlan and HIV ones, so activate them. BF promo intervention was also non-impact.

        required_mod_vars = {
            iccl.IC_CS_IVInfoTag: projection[iccl.IC_CS_IVInfoTag],
            iccl.IC_CS_SelectedIVSetTag: projection[iccl.IC_CS_SelectedIVSetTag],
        }

        interv_to_exclude = []

        for mstID in acu.GBRange(iccl.CS_FirstFPMstID, iccl.CS_LastFPMstID):
            interv_to_exclude.append(mstID)

        interv_to_exclude.append(iccl.CS_FirstAMMstID)
        interv_to_exclude.append(iccl.CS_MstPercOnART)
        interv_to_exclude.append(int(iccl.CS_IV_PMTCT_MST_ID))
        interv_to_exclude.append(int(iccl.CS_IV_Cotrimoxazole_MST_ID))

        icul.IC_CS_set_interventions_active(required_mod_vars, interv_to_exclude)

        BF_promo_interv_rec = icmvu.get_IC_interv_rec(
            projection[icmvt.IC_INTERV_RECORDS_TAG], icii.IC_IV_ChangesInBF_MST_ID
        )
        if BF_promo_interv_rec != gbc.GB_NOT_FOUND:
            icmvu.set_IC_impact_interv(BF_promo_interv_rec, True)

        # Added 2/11/2025: IHT now shows part of LiST.  There's a checkbox for entering direct BF prevalence.  It should have defaulted on but defaulted off.  If off, there's also a special
        # mstID for BF promotion that should be in the selected intervention set and a MV used in calcs that needs to be set to promotion.

        # If direct entry of BF is not being used, assume promotion should be on.
        if iccl.IC_CS_MstDirectEntryOfBF not in projection[iccl.IC_CS_SelectedIVSetTag]:
            projection[iccl.IC_CS_SelectedIVSetTag].append(iccl.IC_CS_MstBFPromotion)
            projection[iccl.IC_CS_EnterBFImproveDataTag] = iccl.IC_CS_MstBFPromotionMode

    if IC_DRUG_SUPPLY_RECORDS_TAG_V1 in projection:
        _convert_drug_supply_records_1(projection, IC_DRUG_SUPPLY_RECORDS_TAG_V1)
        _convert_drug_supply_records_2(projection, icmvt.IC_DRUG_SUPPLY_RECORDS_TAG)

    elif IC_DRUG_SUPPLY_RECORDS_TAG_V2 in projection:
        _convert_drug_supply_records_2(projection, IC_DRUG_SUPPLY_RECORDS_TAG_V2)

    # Drug and supply treatment input records

    if IC_TREAT_INPUT_DRUG_SUPPLY_RECORDS_TAG_V1 in projection:
        # String constants were added for drugs and supplies, treatment input groups, and treatment inputs. Add them if they don't exist in those structures.
        TI_drug_supply_records = projection[IC_TREAT_INPUT_DRUG_SUPPLY_RECORDS_TAG_V1]

        for rec in TI_drug_supply_records:
            if icmvf.IC_TI_NOTE_STR_CONST not in rec:
                rec[icmvf.IC_TI_NOTE_STR_CONST] = ""

        projection[icmvt.IC_TREAT_INPUT_DRUG_SUPPLY_RECORDS_TAG] = deepcopy(TI_drug_supply_records)

    # Medical personnel treatment input records

    if IC_TREAT_INPUT_MED_PERSONNEL_RECORDS_TAG_V1 in projection:
        # String constants were added for drugs and supplies, treatment input groups, and treatment inputs. Add them if they don't exist in those structures.
        TI_med_personnel_records = projection[IC_TREAT_INPUT_MED_PERSONNEL_RECORDS_TAG_V1]

        for rec in TI_med_personnel_records:
            if icmvf.IC_TI_NOTE_STR_CONST not in rec:
                rec[icmvf.IC_TI_NOTE_STR_CONST] = ""

        projection[icmvt.IC_TREAT_INPUT_MED_PERSONNEL_RECORDS_TAG] = deepcopy(TI_med_personnel_records)

    # Outpatient visit/inpatient day treatment input records

    if IC_TREAT_INPUT_OUTPAT_INPAT_RECORDS_TAG_V1 in projection:
        # String constants were added for drugs and supplies, treatment input groups, and treatment inputs. Add them if they don't exist in those structures.
        TI_outpat_inpat_records = projection[IC_TREAT_INPUT_OUTPAT_INPAT_RECORDS_TAG_V1]

        for rec in TI_outpat_inpat_records:
            if icmvf.IC_TI_NOTE_STR_CONST not in rec:
                rec[icmvf.IC_TI_NOTE_STR_CONST] = ""

        projection[icmvt.IC_TREAT_INPUT_OUTPAT_INPAT_RECORDS_TAG] = deepcopy(TI_outpat_inpat_records)

    # Drug and supply group records

    if IC_TREAT_INPUT_GROUP_DRUG_SUPPLY_RECORDS_TAG_V1 in projection:
        # String constants were added for drugs and supplies, treatment input groups, and treatment inputs. Add them if they don't exist in those structures.
        TIG_drug_supply_records = projection[IC_TREAT_INPUT_GROUP_DRUG_SUPPLY_RECORDS_TAG_V1]

        for rec in TIG_drug_supply_records:
            if icmvf.IC_TIG_STR_CONST not in rec:
                rec[icmvf.IC_TIG_STR_CONST] = ""

        projection[icmvt.IC_TREAT_INPUT_GROUP_DRUG_SUPPLY_RECORDS_TAG] = deepcopy(TIG_drug_supply_records)

    # Medical personnel group records

    if IC_TREAT_INPUT_GROUP_MED_PERSONNEL_RECORDS_TAG_V1 in projection:
        # String constants were added for drugs and supplies, treatment input groups, and treatment inputs. Add them if they don't exist in those structures.
        TIG_med_personnel_records = projection[IC_TREAT_INPUT_GROUP_MED_PERSONNEL_RECORDS_TAG_V1]

        for rec in TIG_med_personnel_records:
            if icmvf.IC_TIG_STR_CONST not in rec:
                rec[icmvf.IC_TIG_STR_CONST] = ""

        projection[icmvt.IC_TREAT_INPUT_GROUP_MED_PERSONNEL_RECORDS_TAG] = deepcopy(TIG_med_personnel_records)

    # Outpatient visit/inpatient day group records

    if IC_TREAT_INPUT_GROUP_OUTPAT_INPAT_RECORDS_TAG_V1 in projection:
        # String constants were added for drugs and supplies, treatment input groups, and treatment inputs. Add them if they don't exist in those structures.
        TIG_outpat_inpat_records = projection[IC_TREAT_INPUT_GROUP_OUTPAT_INPAT_RECORDS_TAG_V1]

        for rec in TIG_outpat_inpat_records:
            if icmvf.IC_TIG_STR_CONST not in rec:
                rec[icmvf.IC_TIG_STR_CONST] = ""

        projection[icmvt.IC_TREAT_INPUT_GROUP_OUTPAT_INPAT_RECORDS_TAG] = deepcopy(TIG_outpat_inpat_records)

    if icmvt.IC_TARG_POP_RECORDS_TAG in projection:
        targ_pop_records_mv = projection[icmvt.IC_TARG_POP_RECORDS_TAG]

        TB_costing_on_mv = projection[pjmvt.GB_TBCostingOnTag]
        IHT_on_mv = projection[pjmvt.GB_IHTOnTag]

        found_355 = False
        found_356 = False
        found_357 = False

        # Target populations' meanings changed. Normally, we'd just make new target populations, but the ones we started with may not have
        # been available in the first place, so better to change them this time (and notice is short).
        for rec in targ_pop_records_mv:
            # Pulmonary and extrapulmonary TB, adults 15+: Number presumed rifampicin- and isoniazid-sensitive
            if rec["defTargPopMstID"] == 355:
                rec["name"] = (
                    "Pulmonary and extrapulmonary TB, adults 15+: Number presumed rifampicin- and isoniazid-sensitive"
                )
                rec["stringConstant"] = "GB_stPulmExtrapulmTBAdults15PPresRifampIsonSens"
                found_355 = True

            # Pulmonary and extrapulmonary TB, children 0-14: Number presumed rifampicin- and isoniazid-sensitive
            elif rec["defTargPopMstID"] == 356:
                rec["name"] = (
                    "Pulmonary and extrapulmonary TB, children 0-14: Number presumed rifampicin- and isoniazid-sensitive"
                )
                rec["stringConstant"] = "GB_stPulmExtrapulmTBChild0t14PresRifampIsonSens"
                found_356 = True

            # Pulmonary and extrapulmonary TB, children 0-14, without severe TB: Number presumed rifampicin- and isoniazid-sensitive
            elif rec["defTargPopMstID"] == 357:
                rec["name"] = (
                    "Pulmonary and extrapulmonary TB, children 0-14, without severe TB: Number presumed rifampicin- and isoniazid-sensitive"
                )
                rec["stringConstant"] = "GB_stPulmExtrapulmTBChild0t14NotSevPresRifampIsonSens"
                found_357 = True

        if TB_costing_on_mv or IHT_on_mv:
            # Forgot to add these new target populations for existing projections. There may be more elegant solutions (such as loading missing targ pops
            # from default database), but need to do the fastest one now, as we are in a time crunch.
            if not found_355:
                rec = {}
                rec["name"] = (
                    "Pulmonary and extrapulmonary TB, adults 15+: Number presumed rifampicin- and isoniazid-sensitive"
                )
                rec["stringConstant"] = "GB_stPulmExtrapulmTBAdults15PPresRifampIsonSens"
                rec["defTargPopMstID"] = 355
                rec["applicProgAreaIDs"] = ["22" if IHT_on_mv else "1"]
                rec["requiredModMstIDs"] = ["24"]
                targ_pop_records_mv.append(rec)

            if not found_356:
                rec = {}
                rec["name"] = (
                    "Pulmonary and extrapulmonary TB, children 0-14: Number presumed rifampicin- and isoniazid-sensitive"
                )
                rec["stringConstant"] = "GB_stPulmExtrapulmTBChild0t14PresRifampIsonSens"
                rec["defTargPopMstID"] = 356
                rec["applicProgAreaIDs"] = ["22" if IHT_on_mv else "1"]
                rec["requiredModMstIDs"] = ["24"]
                targ_pop_records_mv.append(rec)

            if not found_357:
                rec = {}
                rec["name"] = (
                    "Pulmonary and extrapulmonary TB, children 0-14, without severe TB: Number presumed rifampicin- and isoniazid-sensitive"
                )
                rec["stringConstant"] = "GB_stPulmExtrapulmTBChild0t14NotSevPresRifampIsonSens"
                rec["defTargPopMstID"] = 357
                rec["applicProgAreaIDs"] = ["22" if IHT_on_mv else "1"]
                rec["requiredModMstIDs"] = ["24"]
                targ_pop_records_mv.append(rec)

    if gbc.GB_TB in projection[pjmvt.PJN_ModulesTag]:
        # "Resistance testing: Bedaquiline, linezolid, levofloxacin, moxifloxacin" was not correctly marked as an
        # impact intervention in the intervention database. Add special case and flag appropriately to ensure
        # that coverage transfer works correctly for this intervention.
        interv_records_value = projection[icmvt.IC_INTERV_RECORDS_TAG]
        interv_rec = icmvu.get_IC_interv_rec(
            interv_records_value, ictii.IC_TI_IV_RESIST_TEST_BEDAQ_LINEZ_LEVO_MOXI_MST_ID
        )
        if interv_rec != gbc.GB_NOT_FOUND:
            special_cases = icmvu.get_IC_interv_special_cases(interv_rec)
            impact_interv = icmvu.get_IC_impact_interv(interv_rec)
            if icc.IC_TB_IMPACT not in special_cases:
                icmvu.add_IC_interv_special_case(interv_rec, icc.IC_TB_IMPACT)
            if not impact_interv:
                icmvu.set_IC_impact_interv(interv_rec, True)

    # delete tags
    for tag in IC_TagsForDeletion:
        if tag in projection:
            del projection[tag]

    return projection


# Old tags
IC_INTERV_RECORDS_TAG_V1 = "<IC_InterventionRecords_V1>"
IC_INTERV_RECORDS_TAG_V2 = "<IC_InterventionRecords_V2>"
IC_INTERV_RECORDS_TAG_V3 = "<IC_InterventionRecords_V3>"
IC_DRUG_SUPPLY_RECORDS_TAG_V1 = "<IC_DrugSupplyRecords_V1>"
IC_DRUG_SUPPLY_RECORDS_TAG_V2 = "<IC_DrugSupplyRecords_V2>"
IC_TREAT_INPUT_DRUG_SUPPLY_RECORDS_TAG_V1 = "<IC_TreatInputDrugSupplyRecords_V1>"
IC_TREAT_INPUT_MED_PERSONNEL_RECORDS_TAG_V1 = "<IC_TreatInputMedPersonnelRecords_V1>"
IC_TREAT_INPUT_OUTPAT_INPAT_RECORDS_TAG_V1 = "<IC_TreatInputOutpatInpatRecords_V1>"
IC_TREAT_INPUT_GROUP_DRUG_SUPPLY_RECORDS_TAG_V1 = "<IC_TreatInputGroupDrugSupplyRecords_V1>"
IC_TREAT_INPUT_GROUP_MED_PERSONNEL_RECORDS_TAG_V1 = "<IC_TreatInputGroupMedPersonnelRecords_V1>"
IC_TREAT_INPUT_GROUP_OUTPAT_INPAT_RECORDS_TAG_V1 = "<IC_TreatInputGroupOutpatInpatRecords_V1>"

IC_TagsForDeletion = [
    IC_INTERV_RECORDS_TAG_V1,
    IC_INTERV_RECORDS_TAG_V2,
    IC_INTERV_RECORDS_TAG_V3,
    IC_DRUG_SUPPLY_RECORDS_TAG_V1,
    IC_DRUG_SUPPLY_RECORDS_TAG_V2,
    IC_TREAT_INPUT_DRUG_SUPPLY_RECORDS_TAG_V1,
    IC_TREAT_INPUT_MED_PERSONNEL_RECORDS_TAG_V1,
    IC_TREAT_INPUT_OUTPAT_INPAT_RECORDS_TAG_V1,
    IC_TREAT_INPUT_GROUP_DRUG_SUPPLY_RECORDS_TAG_V1,
    IC_TREAT_INPUT_GROUP_MED_PERSONNEL_RECORDS_TAG_V1,
    IC_TREAT_INPUT_GROUP_OUTPAT_INPAT_RECORDS_TAG_V1,
]


def _convert_interv_records_1(projection, interv_records_tag):
    #  "TB preventive treatment, MDR/RR TB strain" is now a non-impact intervention.
    interv_records_value = projection[interv_records_tag]

    interv_rec = icmvu.get_IC_interv_rec(interv_records_value, ictii.IC_TI_IV_TBOralPrevMedWRifampDrugResist_MST_ID)

    if interv_rec != gbc.GB_NOT_FOUND:
        icmvu.set_IC_impact_interv(interv_rec, False)

    # Aa special case telling the client that the "TB preventive treatment, adults", "TB preventive treatment, children 0-14" interventions' coverages should be
    # locked did not exist. If this flag is not in the specialCases set for these interventions, add it.
    interv_rec = icmvu.get_IC_interv_rec(interv_records_value, ictii.IC_TI_IV_TB_ORAL_PREV_MED_ADULTS_15_PLUS_MST_ID)

    if interv_rec != gbc.GB_NOT_FOUND:
        icmvu.add_IC_interv_special_case(interv_rec, icc.IC_LOCK_COVERAGES)

    interv_rec = icmvu.get_IC_interv_rec(interv_records_value, ictii.IC_TI_IV_TB_ORAL_PREV_MED_CHILDREN_0_14_MST_ID)

    if interv_rec != gbc.GB_NOT_FOUND:
        icmvu.add_IC_interv_special_case(interv_rec, icc.IC_LOCK_COVERAGES)

    if interv_records_tag != icmvt.IC_INTERV_RECORDS_TAG:
        projection[icmvt.IC_INTERV_RECORDS_TAG] = deepcopy(interv_records_value)


def _convert_interv_records_2(projection, interv_records_tag):
    # Correction for issue where interventions were being created with a percent delivery channel distribution field that was the wrong length.
    interv_records_value = projection[interv_records_tag]
    deliv_chan_records_value = projection[ihmvt.IH_DELIV_CHAN_RECORDS_TAG_V1]

    num_deliv_chans_total = len(deliv_chan_records_value) + icc.IC_NUM_DELIV_CHANS

    for rec in interv_records_value:
        diff = num_deliv_chans_total - len(rec[icmvf.IC_INTERV_PERC_DELIV_THROUGH_CHAN])

        if num_deliv_chans_total > len(rec[icmvf.IC_INTERV_PERC_DELIV_THROUGH_CHAN]):
            for i in acu.GBRange(1, diff):
                rec[icmvf.IC_INTERV_PERC_DELIV_THROUGH_CHAN].append([0] * icc.IC_NUM_YEAR_ENDPOINTS)

        elif num_deliv_chans_total < len(rec[icmvf.IC_INTERV_PERC_DELIV_THROUGH_CHAN]):
            for i in acu.GBRange(1, diff):
                rec[icmvf.IC_INTERV_PERC_DELIV_THROUGH_CHAN].pop()

    if interv_records_tag != icmvt.IC_INTERV_RECORDS_TAG:
        projection[icmvt.IC_INTERV_RECORDS_TAG] = deepcopy(interv_records_value)


def _convert_drug_supply_records_1(projection, drug_supply_records_tag):
    # String constants were added for drugs and supplies, treatment input groups, and treatment inputs. Add them if they don't exist in those structures.
    drug_supply_records_value = projection[drug_supply_records_tag]

    for rec in drug_supply_records_value:
        if icmvf.IC_DRUG_SUPPLY_STR_CONST not in rec:
            rec[icmvf.IC_DRUG_SUPPLY_STR_CONST] = ""

    if drug_supply_records_tag != icmvt.IC_DRUG_SUPPLY_RECORDS_TAG:
        projection[icmvt.IC_DRUG_SUPPLY_RECORDS_TAG] = deepcopy(drug_supply_records_value)


def _convert_drug_supply_records_2(projection, drug_supply_records_tag):
    # For TB app, we added two new fields to the drug and supply records.
    drug_supply_records_value = projection[drug_supply_records_tag]

    first_year_mv_value = projection[pjmvt.PJN_FirstYearTag]
    final_year_mv_value = projection[pjmvt.PJN_FinalYearTag]

    num_years = final_year_mv_value - first_year_mv_value + 1

    if projection[pjmvt.GB_TBCostingOnTag]:
        for rec in drug_supply_records_value:
            if icmvf.IC_DRUG_SUPPLY_LOG_SUPP_CHAIN_COSTS_PERC not in rec:
                rec[icmvf.IC_DRUG_SUPPLY_LOG_SUPP_CHAIN_COSTS_PERC] = 0

            if icmvf.IC_DRUG_SUPPLY_WASTAGE_PERC not in rec:
                rec[icmvf.IC_DRUG_SUPPLY_WASTAGE_PERC] = 0

    # Several fields were added for Logistics. To make things easier, since Logistics can be turned on and off and the fields aren't huge,
    # just add them to all drug and supply records in all modes if they are not there.

    for rec in drug_supply_records_value:
        if icmvf.IC_DRUG_SUPPLY_PERC_WASTAGE not in rec:
            rec[icmvf.IC_DRUG_SUPPLY_PERC_WASTAGE] = 0

        if icmvf.IC_DRUG_SUPPLY_PERC_SAFETY_STOCK_NEEDED not in rec:
            rec[icmvf.IC_DRUG_SUPPLY_PERC_SAFETY_STOCK_NEEDED] = 0

        if icmvf.IC_DRUG_SUPPLY_SAFETY_STOCK_BASELINE not in rec:
            rec[icmvf.IC_DRUG_SUPPLY_SAFETY_STOCK_BASELINE] = 0

        if icmvf.IC_DRUG_SUPPLY_PERC_SAFETY_STOCK_REC not in rec:
            rec[icmvf.IC_DRUG_SUPPLY_PERC_SAFETY_STOCK_REC] = np.full((num_years), 0.0).tolist()

        if icmvf.IC_DRUG_SUPPLY_QUANTITY not in rec:
            rec[icmvf.IC_DRUG_SUPPLY_QUANTITY] = np.full((num_years), 0.0).tolist()

    if drug_supply_records_tag != icmvt.IC_DRUG_SUPPLY_RECORDS_TAG:
        projection[icmvt.IC_DRUG_SUPPLY_RECORDS_TAG] = deepcopy(drug_supply_records_value)


def _convert_interv_records_3(projection, interv_records_tag):
    # A special case telling the client that the "Testing of latent TB infection, other high-risk groups, adults 15+" interventions' coverage should be
    # locked did not exist. If this flag is not in the specialCases set for this intervention, add it.
    interv_records_value = projection[interv_records_tag]

    interv_rec = icmvu.get_IC_interv_rec(interv_records_value, ictii.IC_TI_IV_TestLatentTBOtherHRGsAdults15Plus_MST_ID)

    if interv_rec != gbc.GB_NOT_FOUND:
        icmvu.add_IC_interv_special_case(interv_rec, icc.IC_LOCK_COVERAGES)

    if interv_records_tag != icmvt.IC_INTERV_RECORDS_TAG:
        projection[icmvt.IC_INTERV_RECORDS_TAG] = deepcopy(interv_records_value)
