# Complete PYOMO implementation

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

def school_player_optimization():
    """Optimize player assignments to school teams to maximize performance score."""
    
    # 1. MODEL CREATION
    model = pyo.ConcreteModel()
    
    # 2. DATA SETUP
    # Data from the database schema
    player_ids = [1, 2, 3]
    team_ids = [1, 2, 3]
    performance_coefficients = {1: 1.8, 2: 2.3, 3: 2.7}
    ages = {1: 16, 2: 17, 3: 18}
    max_team_sizes = {1: 15, 2: 18, 3: 20}
    max_age_limits = {1: 100, 2: 110, 3: 120}
    
    # CRITICAL: Validate array lengths before indexing
    assert len(player_ids) == len(performance_coefficients) == len(ages), "Array length mismatch"
    assert len(team_ids) == len(max_team_sizes) == len(max_age_limits), "Array length mismatch"
    
    # 3. SETS
    model.I = pyo.Set(initialize=player_ids)
    model.J = pyo.Set(initialize=team_ids)
    
    # 4. PARAMETERS
    model.performance_coefficient = pyo.Param(model.I, initialize=performance_coefficients)
    model.age = pyo.Param(model.I, initialize=ages)
    model.max_team_size = pyo.Param(model.J, initialize=max_team_sizes)
    model.max_age_limit = pyo.Param(model.J, initialize=max_age_limits)
    
    # 5. VARIABLES
    model.x = pyo.Var(model.I, model.J, within=pyo.Binary)
    
    # 6. OBJECTIVE FUNCTION
    def obj_rule(model):
        return sum(model.performance_coefficient[i] * model.x[i, j] for i in model.I for j in model.J)
    model.objective = pyo.Objective(rule=obj_rule, sense=pyo.maximize)
    
    # 7. CONSTRAINTS
    
    # Team Size Constraints
    def team_size_rule(model, j):
        return sum(model.x[i, j] for i in model.I) <= model.max_team_size[j]
    model.team_size_constraint = pyo.Constraint(model.J, rule=team_size_rule)
    
    # Age Limit Constraints
    def age_limit_rule(model, j):
        return sum(model.age[i] * model.x[i, j] for i in model.I) <= model.max_age_limit[j]
    model.age_limit_constraint = pyo.Constraint(model.J, rule=age_limit_rule)
    
    # Player Assignment Constraints
    def player_assignment_rule(model, i):
        return sum(model.x[i, j] for j in model.J) <= 1
    model.player_assignment_constraint = pyo.Constraint(model.I, rule=player_assignment_rule)
    
    # 8. SOLVING WITH GUROBI
    solver = SolverFactory('gurobi')
    
    # Optional: Set solver options
    solver.options['TimeLimit'] = 300  # 5 minutes
    solver.options['MIPGap'] = 0.01    # 1% gap
    
    # Solve the model
    results = solver.solve(model, tee=True)  # tee=True shows solver output
    
    # 9. RESULT PROCESSING
    # Check solver status
    if results.solver.termination_condition == pyo.TerminationCondition.optimal:
        print("Optimal solution found!")
        print(f"Optimal value: {pyo.value(model.objective)}")
        
        # Extract variable values
        print("\nPlayer assignments:")
        for i in model.I:
            for j in model.J:
                x_val = pyo.value(model.x[i, j])
                if x_val > 0.5:  # Only print assignments
                    print(f"Player {i} assigned to Team {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}")
    
    return model

# Run the optimization
school_player_optimization()