can you check this code for error 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_latin_square(n):
    """Generates a Latin Square of size n."""
    latin_square = [[(i + j) % n for j in range(n)] for i in range(n)]
    return latin_square

def generate_schedule(num_teams, num_activities):
    num_rounds = num_activities

    # Step 1: Generate list of teams
    teams = [f"T{t}" for t in range(1, num_teams + 1)]

    # Step 2: Generate a Latin Square for activity assignments
    latin_square = generate_latin_square(num_activities)

    # Step 3: Build the schedule using the Latin Square
    schedule = []
    matchup_history = {}

    for round_num in range(num_rounds):
        round_schedule = {}
        activity_teams = {}

        # Rotate the teams according to the Latin Square
        for idx, team in enumerate(teams):
            activity = latin_square[idx % num_activities][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)

        # Step 4: Shuffle and pair teams in each activity
        for activity_name, team_list in activity_teams.items():
            random.shuffle(team_list)
            while len(team_list) >= 2:
                team1 = team_list.pop()
                team2 = team_list.pop()
                matchup = tuple(sorted([team1, team2]))
                # Ensure the same teams don't face each other again
                while matchup in matchup_history:
                    team_list.insert(0, team2)
                    team2 = team_list.pop()
                    matchup = tuple(sorted([team1, team2]))
                round_schedule[activity_name] = f"{team1} vs {team2}"
                matchup_history[matchup] = True

            # Handle byes if an odd number of teams in an activity
            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)
    if schedule:
        print("\nGenerated Schedule:")
        print_schedule(schedule)
    else:
        print("No schedule could be generated. Please check the input parameters.")

    # 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()