<gh_stars>1-10
import os

import pandas as pd
from datetime import datetime


def stripTags(string):
    if "<" in string and ">" in string and string.find("<") < string.find(">"):
        iFirst = string.find("<")
        iEnd = string.find(">")
        strOut = string[:iFirst] + string[iEnd + 1:]
        return stripTags(strOut)
    else:
        return string


def removeDayTag(strIn):
    first2 = strIn[1:3].isdigit()
    first3 = strIn[1:4].isdigit()
    first4 = strIn[1:5].isdigit()
    if first4:
        return strIn[3:]
    elif first3:
        return strIn[2:]
    elif first2:
        return strIn[3:]
    else:
        return strIn[2:]


def getDay(strIn):
    first1 = strIn[1:2].isdigit()
    first2 = strIn[1:3].isdigit()
    first3 = strIn[1:4].isdigit()
    first4 = strIn[1:5].isdigit()
    if first4:
        return int(strIn[1:3])
    elif first3:
        return int(strIn[1:2])
    elif first2:
        return int(strIn[1:3])
    else:
        return int(strIn[1:2])


def checkReferenceBranching(strIn):
    conditions = strIn.split("or")
    dictOut = {}
    for i in range(len(conditions)):
        iOpenBracket = conditions[i].find("[")
        iCloseBracket = conditions[i].find("]")
        varField = removeDayTag(conditions[i][iOpenBracket + 1:iCloseBracket])
        varAns = conditions[i][iCloseBracket + 1:]
        if "=" in varAns:
            if "'" in varAns:
                iOpenStr = varAns.find("'")
                iCloseStr = varAns.rfind("'")
                varAnsInt = int(varAns[iOpenStr + 1:iCloseStr])
            elif '"' in varAns:
                iOpenStr = varAns.find('"')
                iCloseStr = varAns.rfind('"')
                varAnsInt = int(varAns[iOpenStr + 1:iCloseStr])
            dictOut[varField] = varAnsInt
        else:
            dictOut[varField] = "<>"
    return dictOut


def checkSelfBranching(strIn, expDay):
    conditions = strIn.split("or")
    lstOut = []
    for i in range(len(conditions)):
        if "=" in conditions[i]:
            iOpenBracket = conditions[i].find("[")
            iCloseBracket = conditions[i].find("]")
            varField = getDay(conditions[i][iOpenBracket + 1:iCloseBracket])
            lstOut.append(varField)
        else:
            lstOut.append(expDay)
    return [i for i, x in enumerate(lstOut) if x == expDay]


def normalizeEntry(strIn):
    strIn = str(strIn)
    strIn = strIn.strip()
    return strIn


if __name__ == "__main__":
    while True:
        usrIn = input("Enter a data dictionary path or 'quit' to quit program: ")
        if usrIn == 'quit':
            break
        else:
            try:
                baseDF = pd.read_csv(usrIn)
            except Exception as e:
                print(e)
                continue
            else:
                # Generating file name
                currDateTime = datetime.now().strftime("%Y-%m-%d_%I-%M-%S-%p")
                absFilepath = os.path.join(os.getcwd(), f"W4_DataDictionary_Check_{currDateTime}.txt")
                print(f"Collecting values from {usrIn}")
                baseDF = pd.read_csv(usrIn, low_memory=False)
                day1 = pd.DataFrame(columns=baseDF.columns)
                day2 = pd.DataFrame(columns=baseDF.columns)
                day3 = pd.DataFrame(columns=baseDF.columns)
                day4 = pd.DataFrame(columns=baseDF.columns)
                day5 = pd.DataFrame(columns=baseDF.columns)
                day6 = pd.DataFrame(columns=baseDF.columns)
                day7 = pd.DataFrame(columns=baseDF.columns)
                day8 = pd.DataFrame(columns=baseDF.columns)
                day9 = pd.DataFrame(columns=baseDF.columns)
                day10 = pd.DataFrame(columns=baseDF.columns)
                day11 = pd.DataFrame(columns=baseDF.columns)
                day12 = pd.DataFrame(columns=baseDF.columns)
                day13 = pd.DataFrame(columns=baseDF.columns)
                day14 = pd.DataFrame(columns=baseDF.columns)

                for index, row in baseDF.iterrows():
                    if row["Form Name"] == "day_1_monday_daily_survey":
                        row['Variable / Field Name'] = row['Variable / Field Name'][2:]
                        day1 = day1.append(row)
                    if "day_2" in row["Form Name"]:
                        row['Variable / Field Name'] = row['Variable / Field Name'][2:]
                        day2 = day2.append(row)
                    if "day_3" in row["Form Name"]:
                        row['Variable / Field Name'] = row['Variable / Field Name'][2:]
                        day3 = day3.append(row)
                    if "day_4" in row["Form Name"]:
                        row['Variable / Field Name'] = row['Variable / Field Name'][2:]
                        day4 = day4.append(row)
                    if "day_5" in row["Form Name"]:
                        row['Variable / Field Name'] = row['Variable / Field Name'][2:]
                        day5 = day5.append(row)
                    if "day_6" in row["Form Name"]:
                        row['Variable / Field Name'] = row['Variable / Field Name'][2:]
                        day6 = day6.append(row)
                    if "day_7" in row["Form Name"]:
                        row['Variable / Field Name'] = row['Variable / Field Name'][2:]
                        day7 = day7.append(row)
                    if "day_8" in row["Form Name"]:
                        row['Variable / Field Name'] = row['Variable / Field Name'][2:]
                        day8 = day8.append(row)
                    if "day_9" in row["Form Name"]:
                        row['Variable / Field Name'] = row['Variable / Field Name'][2:]
                        day9 = day9.append(row)
                    if "day_10" in row["Form Name"]:
                        row['Variable / Field Name'] = row['Variable / Field Name'][3:]
                        day10 = day10.append(row)
                    if "day_11" in row["Form Name"]:
                        row['Variable / Field Name'] = row['Variable / Field Name'][3:]
                        day11 = day11.append(row)
                    if "day_12" in row["Form Name"]:
                        row['Variable / Field Name'] = row['Variable / Field Name'][3:]
                        day12 = day12.append(row)
                    if "day_13" in row["Form Name"]:
                        row['Variable / Field Name'] = row['Variable / Field Name'][3:]
                        day13 = day13.append(row)
                    if "day_14" in row["Form Name"]:
                        row['Variable / Field Name'] = row['Variable / Field Name'][3:]
                        day14 = day14.append(row)
                allDays = [day1, day2, day3, day4, day5, day6, day7, day8, day9, day10, day11, day12, day13, day14]

                for i in range(len(allDays)):
                    newIndex = allDays[i].index - allDays[i].index[0]
                    allDays[i] = allDays[i].set_index(newIndex)

                # Collecting days, putting in otherDays dictionary
                otherDays = {}
                for i in range(1, len(allDays)):
                    otherDays[i + 1] = allDays[i]

                # Process list of variable field names - Day 1 (Referential)
                day1Vars = allDays[0]['Variable / Field Name'].to_list()
                for i in range(len(day1Vars)):
                    day1Vars[i] = str(day1Vars[i])


                with open(absFilepath, "w") as fileOut:
                    # For each day (days 2-14)
                    for day in otherDays:
                        dayHeaderString = "------------------------------------------------------------\n" + '###\n'.join(['' for _ in range(3)]) + f"### Day {day}:\n" + '##\n'.join(['' for _ in range(3)]) + "------------------------------------------------------------ "
                        print(dayHeaderString)
                        fileOut.write("\n" + dayHeaderString)

                        # Process list of variable field names - Day x (Comparison)
                        dayVars = otherDays[day]['Variable / Field Name'].to_list()
                        dayVars = otherDays[day]['Variable / Field Name'].to_list()

                        # Checking for variables in day 1 but not in day x
                        [print(f"Day {day}: Missing t{day}{day1Vars[i]}") for i in range(len(day1Vars)) if
                         not (day1Vars[i] in dayVars)]
                        [fileOut.write(f"\nDay {day}: Missing t{day}{day1Vars[i]}") for i in range(len(day1Vars)) if
                         not (day1Vars[i] in dayVars)]

                        # Checking for variables in day x but not in day 1
                        [print(f"Day 1: Missing t1{dayVars[i]} (referencing t{day}{dayVars[i]})") for i in
                         range(len(dayVars)) if not (dayVars[i] in day1Vars)]
                        [fileOut.write(f"\nDay 1: Missing t1{dayVars[i]} (referencing t{day}{dayVars[i]})") for i in
                         range(len(dayVars)) if not (dayVars[i] in day1Vars)]

                        # Check the order of variables
                        for index, row in otherDays[day].iterrows():
                            if row['Variable / Field Name'] != allDays[0].loc[index, 'Variable / Field Name']:
                                print(
                                    f"MISMATCHED ORDER: Day 1 {allDays[0].loc[index, 'Variable / Field Name']}; Day {day} - {row['Variable / Field Name']} ")
                                fileOut.write(
                                    f"\nMISMATCHED ORDER: Day 1 {allDays[0].loc[index, 'Variable / Field Name']}; Day {day} - {row['Variable / Field Name']} ")

                        # for each variable (field) of a single day
                        for index, row in otherDays[day].iterrows():

                            if pd.Series.all(row == allDays[0].columns):
                                continue

                            currRefVar = pd.Series()

                            # determine the corresponding variable (field) in day 1
                            for _, row2 in allDays[0].iterrows():
                                if row2['Variable / Field Name'] == row['Variable / Field Name']:
                                    currRefVar = row2
                                    break

                            # checking branching logic
                            if pd.isna(row['Branching Logic (Show field only if...)']):
                                if len(currRefVar) > 0 and not pd.isna(
                                        currRefVar['Branching Logic (Show field only if...)']):
                                    print(
                                        f"\n## BRANCHING: Day {day} - {row['Variable / Field Name']} is empty (expected branching)")
                                    fileOut.write(
                                        f"\n\n## BRANCHING: Day {day} - {row['Variable / Field Name']} is empty (expected branching)")
                            elif not len(currRefVar):
                                print(
                                    f"\n## BRANCHING: DAY {day} - {row['Variable / Field Name']} does not have a matching variable in day 1")
                                fileOut.write(
                                    f"\n\n## BRANCHING: DAY {day} - {row['Variable / Field Name']} does not have a matching variable in day 1")
                            else:
                                currDict = checkReferenceBranching(row["Branching Logic (Show field only if...)"])
                                refDict = checkReferenceBranching(currRefVar["Branching Logic (Show field only if...)"])
                                if currDict != refDict:
                                    print(
                                        f"\n## BRANCHING: Day {day} - {row['Variable / Field Name']} Branching Logic does not match day 1")
                                    print(f"\n\tDay {day} - {currDict}")
                                    print(f"\n\tDay 1 - {refDict}")

                                    fileOut.write(
                                        f"\n\n## BRANCHING: Day {day} - {row['Variable / Field Name']} Branching Logic does not match day 1")
                                    fileOut.write(f"\n\n\tDay {day} - {currDict}")
                                    fileOut.write(f"\n\n\tDay 1 - {refDict}")
                                if not checkSelfBranching(row["Branching Logic (Show field only if...)"], day):
                                    print(
                                        f"\n## BRANCHING: Day {day} - {row['Variable / Field Name']} Inconsistent branching requirements (not contained within day):\n\t{row['Branching Logic (Show field only if...)']}")
                                    fileOut.write(
                                        f"\n\n## BRANCHING: Day {day} - {row['Variable / Field Name']} Inconsistent branching requirements (not contained within day):\n\t{row['Branching Logic (Show field only if...)']}")

                            currField = row['Field Label']
                            if not pd.isna(currField):
                                currField = normalizeEntry(currField)

                                if "tuesday" in currField and day % 7 == 3:
                                    currField = currField.replace("tuesday", "sunday")
                                elif "wednesday" in currField and day % 7 == 4:
                                    currField = currField.replace("wednesday", "sunday")
                                elif "thursday" in currField and day % 7 == 5:
                                    currField = currField.replace("thursday", "sunday")
                                elif "friday" in currField and day % 7 == 6:
                                    currField = currField.replace("friday", "sunday")
                                elif "saturday" in currField and day % 7 == 0:
                                    currField = currField.replace("saturday", "sunday")
                                elif "monday" in currField and day % 7 == 2:
                                    currField = currField.replace("monday", "sunday")

                                if "martes" in currField and day % 7 == 3:
                                    currField = currField.replace("martes", "domingo")
                                elif "miercoles" in currField and day % 7 == 4:
                                    currField = currField.replace("miercoles", "domingo")
                                elif "jueves" in currField and day % 7 == 5:
                                    currField = currField.replace("jueves", "domingo")
                                elif "viernes" in currField and day % 7 == 6:
                                    currField = currField.replace("viernes", "domingo")
                                elif "sabado" in currField and day % 7 == 0:
                                    currField = currField.replace("sabado", "domingo")
                                elif "lunes" in currField and day % 7 == 2:
                                    currField = currField.replace("lunes", "domingo")

                                if "miércoles" in currField and day % 7 == 4:
                                    currField = currField.replace("miércoles", "domingo")
                                elif "sábado" in currField and day % 7 == 0:
                                    currField = currField.replace("sábado", "domingo")

                                if "Tuesday" in currField and day % 7 == 3:
                                    currField = currField.replace("Tuesday", "Sunday")
                                elif "Wednesday" in currField and day % 7 == 4:
                                    currField = currField.replace("Wednesday", "Sunday")
                                elif "Thursday" in currField and day % 7 == 5:
                                    currField = currField.replace("Thursday", "Sunday")
                                elif "Friday" in currField and day % 7 == 6:
                                    currField = currField.replace("Friday", "Sunday")
                                elif "Saturday" in currField and day % 7 == 0:
                                    currField = currField.replace("Saturday", "Sunday")
                                elif "Monday" in currField and day % 7 == 2:
                                    currField = currField.replace("Monday", "Sunday")

                                if "Martes" in currField and day % 7 == 3:
                                    currField = currField.replace("Martes", "Domingo")
                                elif "Miercoles" in currField and day % 7 == 4:
                                    currField = currField.replace("Miercoles", "Domingo")
                                elif "Jueves" in currField and day % 7 == 5:
                                    currField = currField.replace("Jueves", "Domingo")
                                elif "Viernes" in currField and day % 7 == 6:
                                    currField = currField.replace("Viernes", "Domingo")
                                elif "Sabado" in currField and day % 7 == 0:
                                    currField = currField.replace("Sabado", "Domingo")
                                elif "Lunes" in currField and day % 7 == 2:
                                    currField = currField.replace("Lunes", "Domingo")

                                elif "Miércoles" in currField and day % 7 == 4:
                                    currField = currField.replace("Miércoles", "Domingo")
                                elif "Sábado" in currField and day % 7 == 0:
                                    currField = currField.replace("Sábado", "Domingo")

                            refField = currRefVar['Field Label']
                            if not pd.isna(refField):
                                refField = normalizeEntry(refField)

                            if pd.isna(currField) and not pd.isna(refField):
                                print(
                                    f"\n## FIELD LABEL: Field label for Day {day} - t{day}{currRefVar['Variable / Field Name']} is empty (expected value)")

                                fileOut.write(
                                    f"\n\n## FIELD LABEL: Day {day} - {currRefVar['Field Label']} is empty (expected value)")
                            elif currField != refField:
                                print(
                                    f"\n## FIELD LABEL: Day {day} - t{day}{currRefVar['Variable / Field Name']} does not match expected field label from Day 1 t1{currRefVar['Variable / Field Name']}")

                                print(f"\n# Day 1 t1{currRefVar['Variable / Field Name']} Field Label:\n{refField}\n# Day {day} t{day}{currRefVar['Variable / Field Name']} Field Label:\n{currField}")

                                fileOut.write(
                                    f"\n\n## FIELD LABEL: Day {day} - t{day}{currRefVar['Variable / Field Name']} does not match expected field label from Day 1 t1{currRefVar['Variable / Field Name']}")
                                fileOut.write(f"\n\n# Day 1 t1{currRefVar['Variable / Field Name']} Field Label:\n{refField}\n# Day {day} t{day}{currRefVar['Variable / Field Name']} Field Label:\n{currField}")

                            currChoice = row["Choices, Calculations, OR Slider Labels"]
                            refChoice = currRefVar["Choices, Calculations, OR Slider Labels"]
                            if not pd.isna(currChoice):
                                currChoice = normalizeEntry(currChoice)
                            if not pd.isna(refChoice):
                                refChoice = normalizeEntry(refChoice)

                            if pd.isna(currChoice) and not pd.isna(refChoice):
                                print(f"\n## CHOICES: Choices for Day {day} - {row['Variable / Field Name']} is empty (expected choices)")
                                fileOut.write(
                                    f"\n\n## CHOICES: Choices for Day {day} - {row['Variable / Field Name']} is empty (expected choices)")

                            elif pd.isna(currChoice) and pd.isna(refChoice):
                                continue
                            elif currChoice != refChoice:
                                print(f"\n## CHOICES: Day {day} - {row['Variable / Field Name']} does not match expected choices from Day 1 t1{currRefVar['Variable / Field Name']}")
                                print(f"\n# Day 1 t1{row['Variable / Field Name']} choices:\n{refChoice}\n# Day {day} t{day}{row['Variable / Field Name']} choices:\n{currChoice}")
                                fileOut.write(
                                    f"\n\n## CHOICES: Day {day} - {row['Variable / Field Name']} does not match expected choices from Day 1 t1{currRefVar['Variable / Field Name']}")
                                fileOut.write(
                                    f"\n\n# Day 1 t1{row['Variable / Field Name']} choices:\n{refChoice}\n# Day {day} t{day}{row['Variable / Field Name']} choices:\n{currChoice}")

                    print("------------------------------------------------------------")
                    fileOut.write("\n------------------------------------------------------------")

                print(f"\nOutput written to {absFilepath}\n")

import os

import pandas as pd
from datetime import datetime


def stripTags(string):
    if "<" in string and ">" in string and string.find("<") < string.find(">"):
        iFirst = string.find("<")
        iEnd = string.find(">")
        strOut = string[:iFirst] + string[iEnd + 1:]
        return stripTags(strOut)
    else:
        return string


def removeDayTag(strIn):
    first2 = strIn[1:3].isdigit()
    first3 = strIn[1:4].isdigit()
    first4 = strIn[1:5].isdigit()
    if first4:
        return strIn[3:]
    elif first3:
        return strIn[2:]
    elif first2:
        return strIn[3:]
    else:
        return strIn[2:]


def getDay(strIn):
    first1 = strIn[1:2].isdigit()
    first2 = strIn[1:3].isdigit()
    first3 = strIn[1:4].isdigit()
    first4 = strIn[1:5].isdigit()
    if first4:
        return int(strIn[1:3])
    elif first3:
        return int(strIn[1:2])
    elif first2:
        return int(strIn[1:3])
    else:
        return int(strIn[1:2])


def checkReferenceBranching(strIn):
    conditions = strIn.split("or")
    dictOut = {}
    for i in range(len(conditions)):
        iOpenBracket = conditions[i].find("[")
        iCloseBracket = conditions[i].find("]")
        varField = removeDayTag(conditions[i][iOpenBracket + 1:iCloseBracket])
        varAns = conditions[i][iCloseBracket + 1:]
        if "=" in varAns:
            if "'" in varAns:
                iOpenStr = varAns.find("'")
                iCloseStr = varAns.rfind("'")
                varAnsInt = int(varAns[iOpenStr + 1:iCloseStr])
            elif '"' in varAns:
                iOpenStr = varAns.find('"')
                iCloseStr = varAns.rfind('"')
                varAnsInt = int(varAns[iOpenStr + 1:iCloseStr])
            dictOut[varField] = varAnsInt
        else:
            dictOut[varField] = "<>"
    return dictOut


def checkSelfBranching(strIn, expDay):
    conditions = strIn.split("or")
    lstOut = []
    for i in range(len(conditions)):
        if "=" in conditions[i]:
            iOpenBracket = conditions[i].find("[")
            iCloseBracket = conditions[i].find("]")
            varField = getDay(conditions[i][iOpenBracket + 1:iCloseBracket])
            lstOut.append(varField)
        else:
            lstOut.append(expDay)
    return [i for i, x in enumerate(lstOut) if x == expDay]


def normalizeEntry(strIn):
    strIn = str(strIn)
    strIn = strIn.strip()
    return strIn


if __name__ == "__main__":
    while True:
        usrIn = input("Enter a data dictionary path or 'quit' to quit program: ")
        if usrIn == 'quit':
            break
        else:
            try:
                baseDF = pd.read_csv(usrIn)
            except Exception as e:
                print(e)
                continue
            else:
                # Generating file name
                currDateTime = datetime.now().strftime("%Y-%m-%d_%I-%M-%S-%p")
                absFilepath = os.path.join(os.getcwd(), f"W4_DataDictionary_Check_{currDateTime}.txt")
                print(f"Collecting values from {usrIn}")
                baseDF = pd.read_csv(usrIn, low_memory=False)
                day1 = pd.DataFrame(columns=baseDF.columns)
                day2 = pd.DataFrame(columns=baseDF.columns)
                day3 = pd.DataFrame(columns=baseDF.columns)
                day4 = pd.DataFrame(columns=baseDF.columns)
                day5 = pd.DataFrame(columns=baseDF.columns)
                day6 = pd.DataFrame(columns=baseDF.columns)
                day7 = pd.DataFrame(columns=baseDF.columns)
                day8 = pd.DataFrame(columns=baseDF.columns)
                day9 = pd.DataFrame(columns=baseDF.columns)
                day10 = pd.DataFrame(columns=baseDF.columns)
                day11 = pd.DataFrame(columns=baseDF.columns)
                day12 = pd.DataFrame(columns=baseDF.columns)
                day13 = pd.DataFrame(columns=baseDF.columns)
                day14 = pd.DataFrame(columns=baseDF.columns)

                for index, row in baseDF.iterrows():
                    if row["Form Name"] == "day_1_monday_daily_survey":
                        row['Variable / Field Name'] = row['Variable / Field Name'][2:]
                        day1 = day1.append(row)
                    if "day_2" in row["Form Name"]:
                        row['Variable / Field Name'] = row['Variable / Field Name'][2:]
                        day2 = day2.append(row)
                    if "day_3" in row["Form Name"]:
                        row['Variable / Field Name'] = row['Variable / Field Name'][2:]
                        day3 = day3.append(row)
                    if "day_4" in row["Form Name"]:
                        row['Variable / Field Name'] = row['Variable / Field Name'][2:]
                        day4 = day4.append(row)
                    if "day_5" in row["Form Name"]:
                        row['Variable / Field Name'] = row['Variable / Field Name'][2:]
                        day5 = day5.append(row)
                    if "day_6" in row["Form Name"]:
                        row['Variable / Field Name'] = row['Variable / Field Name'][2:]
                        day6 = day6.append(row)
                    if "day_7" in row["Form Name"]:
                        row['Variable / Field Name'] = row['Variable / Field Name'][2:]
                        day7 = day7.append(row)
                    if "day_8" in row["Form Name"]:
                        row['Variable / Field Name'] = row['Variable / Field Name'][2:]
                        day8 = day8.append(row)
                    if "day_9" in row["Form Name"]:
                        row['Variable / Field Name'] = row['Variable / Field Name'][2:]
                        day9 = day9.append(row)
                    if "day_10" in row["Form Name"]:
                        row['Variable / Field Name'] = row['Variable / Field Name'][3:]
                        day10 = day10.append(row)
                    if "day_11" in row["Form Name"]:
                        row['Variable / Field Name'] = row['Variable / Field Name'][3:]
                        day11 = day11.append(row)
                    if "day_12" in row["Form Name"]:
                        row['Variable / Field Name'] = row['Variable / Field Name'][3:]
                        day12 = day12.append(row)
                    if "day_13" in row["Form Name"]:
                        row['Variable / Field Name'] = row['Variable / Field Name'][3:]
                        day13 = day13.append(row)
                    if "day_14" in row["Form Name"]:
                        row['Variable / Field Name'] = row['Variable / Field Name'][3:]
                        day14 = day14.append(row)
                allDays = [day1, day2, day3, day4, day5, day6, day7, day8, day9, day10, day11, day12, day13, day14]

                for i in range(len(allDays)):
                    newIndex = allDays[i].index - allDays[i].index[0]
                    allDays[i] = allDays[i].set_index(newIndex)

                # Collecting days, putting in otherDays dictionary
                otherDays = {}
                for i in range(1, len(allDays)):
                    otherDays[i + 1] = allDays[i]

                # Process list of variable field names - Day 1 (Referential)
                day1Vars = allDays[0]['Variable / Field Name'].to_list()
                for i in range(len(day1Vars)):
                    day1Vars[i] = str(day1Vars[i])


                with open(absFilepath, "w") as fileOut:
                    # For each day (days 2-14)
                    for day in otherDays:
                        dayHeaderString = "------------------------------------------------------------\n" + '###\n'.join(['' for _ in range(3)]) + f"### Day {day}:\n" + '##\n'.join(['' for _ in range(3)]) + "------------------------------------------------------------ "
                        print(dayHeaderString)
                        fileOut.write("\n" + dayHeaderString)

                        # Process list of variable field names - Day x (Comparison)
                        dayVars = otherDays[day]['Variable / Field Name'].to_list()
                        dayVars = otherDays[day]['Variable / Field Name'].to_list()

                        # Checking for variables in day 1 but not in day x
                        [print(f"Day {day}: Missing t{day}{day1Vars[i]}") for i in range(len(day1Vars)) if
                         not (day1Vars[i] in dayVars)]
                        [fileOut.write(f"\nDay {day}: Missing t{day}{day1Vars[i]}") for i in range(len(day1Vars)) if
                         not (day1Vars[i] in dayVars)]

                        # Checking for variables in day x but not in day 1
                        [print(f"Day 1: Missing t1{dayVars[i]} (referencing t{day}{dayVars[i]})") for i in
                         range(len(dayVars)) if not (dayVars[i] in day1Vars)]
                        [fileOut.write(f"\nDay 1: Missing t1{dayVars[i]} (referencing t{day}{dayVars[i]})") for i in
                         range(len(dayVars)) if not (dayVars[i] in day1Vars)]

                        # Check the order of variables
                        for index, row in otherDays[day].iterrows():
                            if row['Variable / Field Name'] != allDays[0].loc[index, 'Variable / Field Name']:
                                print(
                                    f"MISMATCHED ORDER: Day 1 {allDays[0].loc[index, 'Variable / Field Name']}; Day {day} - {row['Variable / Field Name']} ")
                                fileOut.write(
                                    f"\nMISMATCHED ORDER: Day 1 {allDays[0].loc[index, 'Variable / Field Name']}; Day {day} - {row['Variable / Field Name']} ")

                        # for each variable (field) of a single day
                        for index, row in otherDays[day].iterrows():

                            if pd.Series.all(row == allDays[0].columns):
                                continue

                            currRefVar = pd.Series()

                            # determine the corresponding variable (field) in day 1
                            for _, row2 in allDays[0].iterrows():
                                if row2['Variable / Field Name'] == row['Variable / Field Name']:
                                    currRefVar = row2
                                    break

                            # checking branching logic
                            if pd.isna(row['Branching Logic (Show field only if...)']):
                                if len(currRefVar) > 0 and not pd.isna(
                                        currRefVar['Branching Logic (Show field only if...)']):
                                    print(
                                        f"\n## BRANCHING: Day {day} - {row['Variable / Field Name']} is empty (expected branching)")
                                    fileOut.write(
                                        f"\n\n## BRANCHING: Day {day} - {row['Variable / Field Name']} is empty (expected branching)")
                            elif not len(currRefVar):
                                print(
                                    f"\n## BRANCHING: DAY {day} - {row['Variable / Field Name']} does not have a matching variable in day 1")
                                fileOut.write(
                                    f"\n\n## BRANCHING: DAY {day} - {row['Variable / Field Name']} does not have a matching variable in day 1")
                            else:
                                currDict = checkReferenceBranching(row["Branching Logic (Show field only if...)"])
                                refDict = checkReferenceBranching(currRefVar["Branching Logic (Show field only if...)"])
                                if currDict != refDict:
                                    print(
                                        f"\n## BRANCHING: Day {day} - {row['Variable / Field Name']} Branching Logic does not match day 1")
                                    print(f"\n\tDay {day} - {currDict}")
                                    print(f"\n\tDay 1 - {refDict}")

                                    fileOut.write(
                                        f"\n\n## BRANCHING: Day {day} - {row['Variable / Field Name']} Branching Logic does not match day 1")
                                    fileOut.write(f"\n\n\tDay {day} - {currDict}")
                                    fileOut.write(f"\n\n\tDay 1 - {refDict}")
                                if not checkSelfBranching(row["Branching Logic (Show field only if...)"], day):
                                    print(
                                        f"\n## BRANCHING: Day {day} - {row['Variable / Field Name']} Inconsistent branching requirements (not contained within day):\n\t{row['Branching Logic (Show field only if...)']}")
                                    fileOut.write(
                                        f"\n\n## BRANCHING: Day {day} - {row['Variable / Field Name']} Inconsistent branching requirements (not contained within day):\n\t{row['Branching Logic (Show field only if...)']}")

                            currField = row['Field Label']
                            if not pd.isna(currField):
                                currField = normalizeEntry(currField)

                                if "tuesday" in currField and day % 7 == 3:
                                    currField = currField.replace("tuesday", "sunday")
                                elif "wednesday" in currField and day % 7 == 4:
                                    currField = currField.replace("wednesday", "sunday")
                                elif "thursday" in currField and day % 7 == 5:
                                    currField = currField.replace("thursday", "sunday")
                                elif "friday" in currField and day % 7 == 6:
                                    currField = currField.replace("friday", "sunday")
                                elif "saturday" in currField and day % 7 == 0:
                                    currField = currField.replace("saturday", "sunday")
                                elif "monday" in currField and day % 7 == 2:
                                    currField = currField.replace("monday", "sunday")

                                if "martes" in currField and day % 7 == 3:
                                    currField = currField.replace("martes", "domingo")
                                elif "miercoles" in currField and day % 7 == 4:
                                    currField = currField.replace("miercoles", "domingo")
                                elif "jueves" in currField and day % 7 == 5:
                                    currField = currField.replace("jueves", "domingo")
                                elif "viernes" in currField and day % 7 == 6:
                                    currField = currField.replace("viernes", "domingo")
                                elif "sabado" in currField and day % 7 == 0:
                                    currField = currField.replace("sabado", "domingo")
                                elif "lunes" in currField and day % 7 == 2:
                                    currField = currField.replace("lunes", "domingo")

                                if "miércoles" in currField and day % 7 == 4:
                                    currField = currField.replace("miércoles", "domingo")
                                elif "sábado" in currField and day % 7 == 0:
                                    currField = currField.replace("sábado", "domingo")

                                if "Tuesday" in currField and day % 7 == 3:
                                    currField = currField.replace("Tuesday", "Sunday")
                                elif "Wednesday" in currField and day % 7 == 4:
                                    currField = currField.replace("Wednesday", "Sunday")
                                elif "Thursday" in currField and day % 7 == 5:
                                    currField = currField.replace("Thursday", "Sunday")
                                elif "Friday" in currField and day % 7 == 6:
                                    currField = currField.replace("Friday", "Sunday")
                                elif "Saturday" in currField and day % 7 == 0:
                                    currField = currField.replace("Saturday", "Sunday")
                                elif "Monday" in currField and day % 7 == 2:
                                    currField = currField.replace("Monday", "Sunday")

                                if "Martes" in currField and day % 7 == 3:
                                    currField = currField.replace("Martes", "Domingo")
                                elif "Miercoles" in currField and day % 7 == 4:
                                    currField = currField.replace("Miercoles", "Domingo")
                                elif "Jueves" in currField and day % 7 == 5:
                                    currField = currField.replace("Jueves", "Domingo")
                                elif "Viernes" in currField and day % 7 == 6:
                                    currField = currField.replace("Viernes", "Domingo")
                                elif "Sabado" in currField and day % 7 == 0:
                                    currField = currField.replace("Sabado", "Domingo")
                                elif "Lunes" in currField and day % 7 == 2:
                                    currField = currField.replace("Lunes", "Domingo")

                                elif "Miércoles" in currField and day % 7 == 4:
                                    currField = currField.replace("Miércoles", "Domingo")
                                elif "Sábado" in currField and day % 7 == 0:
                                    currField = currField.replace("Sábado", "Domingo")

                            refField = currRefVar['Field Label']
                            if not pd.isna(refField):
                                refField = normalizeEntry(refField)

                            if pd.isna(currField) and not pd.isna(refField):
                                print(
                                    f"\n## FIELD LABEL: Field label for Day {day} - t{day}{currRefVar['Variable / Field Name']} is empty (expected value)")

                                fileOut.write(
                                    f"\n\n## FIELD LABEL: Day {day} - {currRefVar['Field Label']} is empty (expected value)")
                            elif currField != refField:
                                print(
                                    f"\n## FIELD LABEL: Day {day} - t{day}{currRefVar['Variable / Field Name']} does not match expected field label from Day 1 t1{currRefVar['Variable / Field Name']}")

                                print(f"\n# Day 1 t1{currRefVar['Variable / Field Name']} Field Label:\n{refField}\n# Day {day} t{day}{currRefVar['Variable / Field Name']} Field Label:\n{currField}")

                                fileOut.write(
                                    f"\n\n## FIELD LABEL: Day {day} - t{day}{currRefVar['Variable / Field Name']} does not match expected field label from Day 1 t1{currRefVar['Variable / Field Name']}")
                                fileOut.write(f"\n\n# Day 1 t1{currRefVar['Variable / Field Name']} Field Label:\n{refField}\n# Day {day} t{day}{currRefVar['Variable / Field Name']} Field Label:\n{currField}")

                            currChoice = row["Choices, Calculations, OR Slider Labels"]
                            refChoice = currRefVar["Choices, Calculations, OR Slider Labels"]
                            if not pd.isna(currChoice):
                                currChoice = normalizeEntry(currChoice)
                            if not pd.isna(refChoice):
                                refChoice = normalizeEntry(refChoice)

                            if pd.isna(currChoice) and not pd.isna(refChoice):
                                print(f"\n## CHOICES: Choices for Day {day} - {row['Variable / Field Name']} is empty (expected choices)")
                                fileOut.write(
                                    f"\n\n## CHOICES: Choices for Day {day} - {row['Variable / Field Name']} is empty (expected choices)")

                            elif pd.isna(currChoice) and pd.isna(refChoice):
                                continue
                            elif currChoice != refChoice:
                                print(f"\n## CHOICES: Day {day} - {row['Variable / Field Name']} does not match expected choices from Day 1 t1{currRefVar['Variable / Field Name']}")
                                print(f"\n# Day 1 t1{row['Variable / Field Name']} choices:\n{refChoice}\n# Day {day} t{day}{row['Variable / Field Name']} choices:\n{currChoice}")
                                fileOut.write(
                                    f"\n\n## CHOICES: Day {day} - {row['Variable / Field Name']} does not match expected choices from Day 1 t1{currRefVar['Variable / Field Name']}")
                                fileOut.write(
                                    f"\n\n# Day 1 t1{row['Variable / Field Name']} choices:\n{refChoice}\n# Day {day} t{day}{row['Variable / Field Name']} choices:\n{currChoice}")

                    print("------------------------------------------------------------")
                    fileOut.write("\n------------------------------------------------------------")

                print(f"\nOutput written to {absFilepath}\n")
# Generating file name # Collecting days, putting in otherDays dictionary # Process list of variable field names - Day 1 (Referential) # For each day (days 2-14) ##\n'.join(['' for _ in range(3)]) + f"### Day {day}:\n" + '##\n'.join(['' for _ in range(3)]) + "------------------------------------------------------------ " # Process list of variable field names - Day x (Comparison) # Checking for variables in day 1 but not in day x # Checking for variables in day x but not in day 1 # Check the order of variables # for each variable (field) of a single day # determine the corresponding variable (field) in day 1 # checking branching logic ## BRANCHING: Day {day} - {row['Variable / Field Name']} is empty (expected branching)") ## BRANCHING: Day {day} - {row['Variable / Field Name']} is empty (expected branching)") ## BRANCHING: DAY {day} - {row['Variable / Field Name']} does not have a matching variable in day 1") ## BRANCHING: DAY {day} - {row['Variable / Field Name']} does not have a matching variable in day 1") ## BRANCHING: Day {day} - {row['Variable / Field Name']} Branching Logic does not match day 1") ## BRANCHING: Day {day} - {row['Variable / Field Name']} Branching Logic does not match day 1") ## BRANCHING: Day {day} - {row['Variable / Field Name']} Inconsistent branching requirements (not contained within day):\n\t{row['Branching Logic (Show field only if...)']}") ## BRANCHING: Day {day} - {row['Variable / Field Name']} Inconsistent branching requirements (not contained within day):\n\t{row['Branching Logic (Show field only if...)']}") ## FIELD LABEL: Field label for Day {day} - t{day}{currRefVar['Variable / Field Name']} is empty (expected value)") ## FIELD LABEL: Day {day} - {currRefVar['Field Label']} is empty (expected value)") ## FIELD LABEL: Day {day} - t{day}{currRefVar['Variable / Field Name']} does not match expected field label from Day 1 t1{currRefVar['Variable / Field Name']}") # Day 1 t1{currRefVar['Variable / Field Name']} Field Label:\n{refField}\n# Day {day} t{day}{currRefVar['Variable / Field Name']} Field Label:\n{currField}") ## FIELD LABEL: Day {day} - t{day}{currRefVar['Variable / Field Name']} does not match expected field label from Day 1 t1{currRefVar['Variable / Field Name']}") # Day 1 t1{currRefVar['Variable / Field Name']} Field Label:\n{refField}\n# Day {day} t{day}{currRefVar['Variable / Field Name']} Field Label:\n{currField}") ## CHOICES: Choices for Day {day} - {row['Variable / Field Name']} is empty (expected choices)") ## CHOICES: Choices for Day {day} - {row['Variable / Field Name']} is empty (expected choices)") ## CHOICES: Day {day} - {row['Variable / Field Name']} does not match expected choices from Day 1 t1{currRefVar['Variable / Field Name']}") # Day 1 t1{row['Variable / Field Name']} choices:\n{refChoice}\n# Day {day} t{day}{row['Variable / Field Name']} choices:\n{currChoice}") ## CHOICES: Day {day} - {row['Variable / Field Name']} does not match expected choices from Day 1 t1{currRefVar['Variable / Field Name']}") # Day 1 t1{row['Variable / Field Name']} choices:\n{refChoice}\n# Day {day} t{day}{row['Variable / Field Name']} choices:\n{currChoice}")