this code is doing its job right but the only problem, its not shuffling the teams from round 2 onward, can you please check the code and fix it while maintain all the rules?                                                                                                                                                             import random
import sys
import csv

try:
    from tabulate import tabulate
except ImportError:
    # Optional dependency
    pass

def validate_inputs(num_teams, num_activities):
    if num_teams % 2 != 0:
        raise ValueError("The number of teams must be an even number.")
    if num_teams < 2 or num_teams > 40:
        raise ValueError("The number of teams must be between 2 and 40.")
    if num_activities < 1 or num_activities > num_teams // 2:
        raise ValueError("The number of activities must be at least 1 and at most half the number of teams.")

def generate_schedule(num_teams, num_activities):
    num_rounds = num_activities

    teams = [f"T{t}" for t in range(1, num_teams + 1)]
    random.shuffle(teams)

    # Create a Latin rectangle of size num_teams x num_rounds
    # Initialize the activity assignments matrix
    activity_assignments = [[-1 for _ in range(num_rounds)] for _ in range(num_teams)]

    # Assign activities ensuring each team plays in each activity exactly once
    for idx in range(num_teams):
        for round_num in range(num_rounds):
            activity = (idx + round_num) % num_activities
            activity_assignments[idx][round_num] = activity

    # Build the schedule
    schedule = []
    matchup_history = {}
    for round_num in range(num_rounds):
        round_schedule = {}
        activity_teams = {}
        for idx, team in enumerate(teams):
            activity = activity_assignments[idx][round_num]
            activity_name = f"Activity {chr(65 + activity)}"
            if activity_name not in activity_teams:
                activity_teams[activity_name] = []
            activity_teams[activity_name].append(team)

        # Pair teams in each activity
        for activity_name, team_list in activity_teams.items():
            random.shuffle(team_list)
            pairs = []
            while len(team_list) >= 2:
                team1 = team_list.pop()
                opponent_found = False
                for i, team2 in enumerate(team_list):
                    matchup = tuple(sorted([team1, team2]))
                    if matchup not in matchup_history:
                        opponent_found = True
                        team_list.pop(i)
                        break
                if not opponent_found:
                    team2 = team_list.pop()
                    matchup = tuple(sorted([team1, team2]))
                else:
                    matchup = tuple(sorted([team1, team2]))
                matchup_history[matchup] = True
                round_schedule[activity_name] = f"{team1} vs {team2}"
            if len(team_list) == 1:
                team = team_list.pop()
                round_schedule[activity_name] = f"{team} has a bye"

        # Fill in 'No match' for any missing activities
        for activity_idx in range(num_activities):
            activity_name = f"Activity {chr(65 + activity_idx)}"
            if activity_name not in round_schedule:
                round_schedule[activity_name] = "No match"
        schedule.append(round_schedule)

    return schedule

def print_schedule(schedule):
    # Prepare table data
    activities = sorted(schedule[0].keys())
    table_headers = ["Round"] + activities
    table_data = []
    for idx, round_schedule in enumerate(schedule):
        row = [f"Round {idx + 1}"] + [round_schedule[activity] for activity in activities]
        table_data.append(row)

    # Try to use tabulate for prettier table
    if 'tabulate' in sys.modules:
        print(tabulate(table_data, headers=table_headers, tablefmt="grid"))
    else:
        # Fallback to plain text
        header_line = '\t'.join(table_headers)
        print(header_line)
        for row in table_data:
            print('\t'.join(row))

def export_schedule(schedule):
    filename = input("Enter filename to export schedule (e.g., schedule.csv): ").strip()
    if not filename:
        print("No filename provided. Skipping export.")
        return
    activities = sorted(schedule[0].keys())
    table_headers = ["Round"] + activities
    with open(filename, 'w', newline='') as csvfile:
        writer = csv.writer(csvfile)
        writer.writerow(table_headers)
        for idx, round_schedule in enumerate(schedule):
            row = [f"Round {idx + 1}"] + [round_schedule[activity] for activity in activities]
            writer.writerow(row)
    print(f"Schedule exported successfully to {filename}")

def main():
    print("Tournament Schedule Generator")
    print("-----------------------------")
    while True:
        try:
            num_teams = int(input("Enter the number of teams (even number up to 40): "))
            num_activities = int(input("Enter the number of activities (<= half the number of teams): "))
            validate_inputs(num_teams, num_activities)
            if num_teams % num_activities != 0:
                print("Warning: Number of teams is not a multiple of number of activities.")
                print("Some rounds may have byes (teams without opponents).")
            break
        except ValueError as ve:
            print(f"Input Error: {ve}")
        except Exception as e:
            print(f"Unexpected error: {e}")
            sys.exit(1)

    schedule = generate_schedule(num_teams, num_activities)
    print("\nGenerated Schedule:")
    print_schedule(schedule)

    # Optional export
    export = input("\nDo you want to export the schedule to a CSV file? (y/n): ").strip().lower()
    if export == 'y':
        export_schedule(schedule)
    else:
        print("Export skipped.")

if __name__ == "__main__":
    main()