# Complete PYOMO implementation - Retry Attempt 4

import pyomo.environ as pyo
from pyomo.opt import SolverFactory

def optimize_tennis_schedule():
    """Optimize tennis match scheduling to minimize travel distance."""
    
    # 1. MODEL CREATION
    model = pyo.ConcreteModel()
    
    # 2. DATA SETUP
    players = [1, 2, 3]
    match_nums = [101, 102, 103]
    
    # Travel distances (player_id, match_num) -> distance
    travel_distances = {
        (1, 101): 12.5,
        (2, 102): 18.0,
        (3, 103): 8.0
    }
    
    # Player availability (player_id -> available_time)
    player_availability = {
        1: 150,
        2: 180,
        3: 120
    }
    
    # Match durations (match_num -> minutes)
    match_durations = {
        101: 90,
        102: 120,
        103: 60
    }
    
    # CRITICAL: Validate array lengths before indexing
    assert len(travel_distances) == len(players), "Array length mismatch for travel distances"
    assert len(player_availability) == len(players), "Array length mismatch for player availability"
    assert len(match_durations) == len(match_nums), "Array length mismatch for match durations"
    
    # 3. SETS
    model.P = pyo.Set(initialize=players)
    model.M = pyo.Set(initialize=match_nums)
    
    # 4. PARAMETERS
    model.travel_distance = pyo.Param(model.P, model.M, initialize=travel_distances, default=0)
    model.available_time = pyo.Param(model.P, initialize=player_availability)
    model.match_duration = pyo.Param(model.M, initialize=match_durations)
    
    # 5. VARIABLES
    model.x = pyo.Var(model.P, model.M, within=pyo.Binary)
    
    # 6. OBJECTIVE FUNCTION
    def obj_rule(model):
        return sum(model.travel_distance[i, j] * model.x[i, j] for i in model.P for j in model.M)
    model.objective = pyo.Objective(rule=obj_rule, sense=pyo.minimize)
    
    # 7. CONSTRAINTS
    
    # Player Time Availability Constraint
    def time_availability_rule(model, i):
        return sum(model.match_duration[j] * model.x[i, j] for j in model.M) <= model.available_time[i]
    model.time_availability_constraint = pyo.Constraint(model.P, rule=time_availability_rule)
    
    # Match Assignment Constraint
    def match_assignment_rule(model, j):
        return sum(model.x[i, j] for i in model.P) == 1
    model.match_assignment_constraint = pyo.Constraint(model.M, rule=match_assignment_rule)
    
    # 8. SOLVING WITH GUROBI
    solver = SolverFactory('gurobi')
    
    # Solve the model
    results = solver.solve(model, tee=True)
    
    # 9. RESULT PROCESSING
    if results.solver.termination_condition == pyo.TerminationCondition.optimal:
        print("Optimal solution found!")
        print(f"Optimal value: {pyo.value(model.objective)}")
        
        # Extract variable values
        print("\nAssignment of players to matches:")
        for i in model.P:
            for j in model.M:
                if pyo.value(model.x[i, j]) > 0.5:  # Binary variable, check if assigned
                    print(f"Player {i} assigned to Match {j}")
        
    elif results.solver.termination_condition == pyo.TerminationCondition.infeasible:
        print("Problem is infeasible")
    elif results.solver.termination_condition == pyo.TerminationCondition.unbounded:
        print("Problem is unbounded")
    else:
        print(f"Solver terminated with condition: {results.solver.termination_condition}")

# Execute the optimization
optimize_tennis_schedule()