Refactor the following code to be cleaner with no redundant code or logic.
CODE:
    for court_type in court_types:
        courts = get_all_courts(ASPXAUTH, court_type)["d"][0]["children"]
        print(courts)
        for court in courts:
            print(court)
            subcourts = get_subcourts(ASPXAUTH, court_type, str(court["key"]).split("$")[0])["d"][0]["children"]
            print('subcourts',subcourts)

            if subcourts[0]['level'] == 'Year':
                years = [int(year['key'].split("$")[0]) for year in subcourts]
                print(years)
                for year in years:
                    print('years',year)
                    moth = 12
                    current_day = 31
                    # if year == 2024:
                    #     moth = datetime.datetime.now().month
                    #     current_day = datetime.datetime.now().day
                    print('m,d',moth,current_day)
                    progress_bar = tqdm(total=(31 * 12),
                                        desc=f'Processing for the court type {court_type} and the court name {str(court["key"]).split("$")[0]} in year {year}')
                    last_completed_day = get_last_completed_day(court_type, str(court["key"]).split("$")[0], year)
                    for month in range(1, moth+1):
                        for day in range(1, current_day+1):
                            if last_completed_day:
                                if day > last_completed_day[1] and month > last_completed_day[0]:
                                    semaphore.acquire()  # acquire the semaphore before starting a new thread
                                    thread = threading.Thread(target=process_day_threaded_safe,
                                                              args=(conn,court_type, court, None, year, month, day))
                                    thread.start()
                                    threads.append(thread)
                                    progress_bar.update(1)
                                else:
                                    progress_bar.update(1)
                            else:
                                semaphore.acquire()  # acquire the semaphore before starting a new thread
                                thread = threading.Thread(target=process_day_threaded_safe,
                                                          args=(conn,court_type, court, None, year, month, day))
                                thread.start()
                                threads.append(thread)
                                progress_bar.update(1)

                    progress_bar.close()

            elif subcourts[0]['level'] == 'YearRange':
                for yearrange in subcourts:
                    min_year = int(str(yearrange['key'].split("$")[0]).split(" - ")[0])
                    max_year = int(str(yearrange['key'].split("$")[0]).split(" - ")[1])
                    print(f"min year {min_year} \n max year {max_year}")
                    # progress_bar = tqdm(total=(((max_year + 1) - min_year) * 31 * 12),
                    #                     desc=f'Processing for the court type {court_type} and the court name {str(court["key"]).split("$")[0]} in year range {str(yearrange["key"].split("$")[0])}')
                    min_year = 2024
                    max_year = 2025
                    for year in range(min_year, max_year + 1):
                        # current_day = 31
                        # if year == 2024:
                        #     moth = datetime.datetime.now().month
                        #     current_day = datetime.datetime.now().day
                        last_completed_day = get_last_completed_day(court_type, str(court["key"]).split("$")[0], year)
                        print('yearrange',year)

                        for month in range(1, 13):
                            print('yearrange month',month)
                            current_day = calendar.monthrange(year, month)[1]

                            for day in range(1, current_day):
                                print('yearrange day',day)

                                if last_completed_day:
                                    print("This is working")
                                    current_date: datetime.date = datetime.date(year, month, day)
                                    today: datetime.date = datetime.date.today()

                                    print('yearrange greater than today',current_date > today)

                                    if current_date > today:
                                        break

                                    last_completed_date = datetime.date(year, last_completed_day[0], last_completed_day[1])
                            
                                    # Convert the current day to a datetime object for comparison
                                    print('last',current_date,last_completed_date)

                                    if current_date > last_completed_date:
                                        print('lprcessing',(day,month))
                                        semaphore.acquire()  # acquire the semaphore before starting a new thread
                                        thread = threading.Thread(target=process_day_threaded_safe,
                                                                    args=(conn,court_type, court, None, year, month, day))
                                        thread.start()
                                        threads.append(thread)
                                        # progress_bar.update(1)
                                    else:
                                        print('not prcessing',(day,month))
                                        # progress_bar.update(1)
                                else:
                                    semaphore.acquire()  # acquire the semaphore before starting a new thread
                                    thread = threading.Thread(target=process_day_threaded_safe,
                                                              args=(conn,court_type, court, None, year, month, day))
                                    thread.start()
                                    threads.append(thread)
                                    # progress_bar.update(1)

                    # progress_bar.close()
            
            else:
                for sub in subcourts:
                    subcourt = str(sub['key'].split("$")[0])
                    years = \
                    get_year_range_for_subcourt(ASPXAUTH, str(court["key"]).split("$")[0], subcourt, court_type)["d"][
                        0]["children"]
                    if years[0]['level'] == 'Year':
                        years = [int(year['key'].split("$")[0]) for year in years]
                        for year in years:
                            moth = 12
                            current_day = 31
                            print(year)
                            # if year == 2024:
                            #     moth = datetime.datetime.now().month
                            #     current_day = datetime.datetime.now().day
                            #     print(moth,current_day)
                            progress_bar = tqdm(total=(31 * 12),
                                                desc=f'Processing for the court type {court_type} and the court name {str(court["key"]).split("$")[0]} for the sub court {subcourt} in year {year}')
                            last_completed_day = get_last_completed_day(court_type, subcourt,year)
                            for month in range(1, moth+1):
                                for day in range(1, current_day+1):
                                    if last_completed_day:
                                        if day > last_completed_day[1] and month > last_completed_day[0]:
                                            semaphore.acquire()  # acquire the semaphore before starting a new thread
                                            thread = threading.Thread(target=process_day_threaded_safe,
                                                                      args=(conn,court_type, court, subcourt, year, month, day))
                                            thread.start()
                                            threads.append(thread)
                                            progress_bar.update(1)
                                        else:
                                            progress_bar.update(1)
                                    else:
                                        semaphore.acquire()  # acquire the semaphore before starting a new thread
                                        thread = threading.Thread(target=process_day_threaded_safe,
                                                                  args=(conn,court_type, court, subcourt, year, month, day))
                                        thread.start()
                                        threads.append(thread)
                                        progress_bar.update(1)

                            progress_bar.close()
                    elif years[0]['level'] == 'YearRange':
                        for yearrange in years:
                            min_year = int(str(yearrange['key'].split("$")[0]).split(" - ")[0])
                            max_year = int(str(yearrange['key'].split("$")[0]).split(" - ")[1])
                            progress_bar = tqdm(total=(((max_year + 1) - min_year) * 31 * 12),
                                                desc=f'Processing for the court type {court_type} and the court name {str(court["key"]).split("$")[0]} for the sub court {subcourt} in year range {str(yearrange["key"].split("$")[0])}')
                            for year in range(min_year, max_year + 1):
                                moth = 12
                                current_day = 31
                                # if year == 2024:
                                #     moth = datetime.datetime.now().month
                                #     current_day = datetime.datetime.now().day
                                last_completed_day = get_last_completed_day(court_type, subcourt, year)
                                for month in range(1, moth+1):
                                    for day in range(1, current_day + 1):
                                        if last_completed_day:
                                            if day > last_completed_day[1] and month > last_completed_day[0]:
                                                semaphore.acquire()  # acquire the semaphore before starting a new thread
                                                thread = threading.Thread(target=process_day_threaded_safe,args=(conn,court_type, court, subcourt, year, month, day))
                                                thread.start()
                                                threads.append(thread)
                                                progress_bar.update(1)
                                            else:
                                                progress_bar.update(1)
                                        else:
                                            semaphore.acquire()  # acquire the semaphore before starting a new thread
                                            thread = threading.Thread(target=process_day_threaded_safe,args=(conn,court_type, court, subcourt, year, month, day))
                                            thread.start()
                                            threads.append(thread)
                                            progress_bar.update(1)

                            progress_bar.close()