# Complete PYOMO implementation - Retry Attempt 4

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

def optimize_club_assignment():
    # 1. MODEL CREATION
    model = pyo.ConcreteModel()
    
    # 2. DATA SETUP
    # Example data from the problem statement
    students = [1, 2, 3]
    clubs = [101, 102, 103]
    
    engagement_scores = {
        (1, 101): 0.6,
        (2, 102): 0.8,
        (3, 103): 0.4
    }
    
    club_capacities = {
        101: 20,
        102: 25,
        103: 15
    }
    
    # CRITICAL: Validate array lengths before indexing
    assert len(engagement_scores) == len(students) * len(clubs), "Engagement scores length mismatch"
    
    # 3. SETS
    model.students = pyo.Set(initialize=students)
    model.clubs = pyo.Set(initialize=clubs)
    
    # 4. PARAMETERS
    model.engagement_scores = pyo.Param(model.students, model.clubs, initialize=engagement_scores)
    model.club_capacities = pyo.Param(model.clubs, initialize=club_capacities)
    
    # 5. VARIABLES
    model.x = pyo.Var(model.students, model.clubs, within=pyo.Binary)
    
    # 6. OBJECTIVE FUNCTION
    def obj_rule(model):
        return sum(model.engagement_scores[s, c] * model.x[s, c] for s in model.students for c in model.clubs)
    model.objective = pyo.Objective(rule=obj_rule, sense=pyo.maximize)
    
    # 7. CONSTRAINTS
    # Club Capacity Constraint
    def club_capacity_rule(model, c):
        return sum(model.x[s, c] for s in model.students) <= model.club_capacities[c]
    model.club_capacity_constraint = pyo.Constraint(model.clubs, rule=club_capacity_rule)
    
    # Student Assignment Constraint
    def student_assignment_rule(model, s):
        return sum(model.x[s, c] for c in model.clubs) <= 1
    model.student_assignment_constraint = pyo.Constraint(model.students, rule=student_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("\nVariable values:")
        for s in model.students:
            for c in model.clubs:
                if pyo.value(model.x[s, c]) > 0:
                    print(f"Student {s} is assigned to Club {c}")
        
    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

# Execute the optimization
optimize_club_assignment()