# Complete PYOMO implementation - Retry Attempt 4

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

def optimize_debate_assignments():
    # 1. MODEL CREATION
    model = pyo.ConcreteModel()
    
    # 2. DATA SETUP
    # Participants
    participants = [101, 102, 103]
    # Debates
    debates = [1, 2, 3]
    # Sides
    sides = ['Affirmative', 'Negative']
    
    # Audience sizes
    audience_sizes = {1: 150, 2: 200, 3: 100}
    # Participant ages
    ages = {101: 25, 102: 30, 103: 35}
    
    # CRITICAL: Validate array lengths before indexing
    assert len(participants) == len(ages), "Array length mismatch"
    assert len(debates) == len(audience_sizes), "Array length mismatch"
    
    # 3. SETS
    model.P = pyo.Set(initialize=participants)  # Participants
    model.D = pyo.Set(initialize=debates)      # Debates
    model.S = pyo.Set(initialize=sides)        # Sides
    
    # 4. PARAMETERS
    model.audience_size = pyo.Param(model.D, initialize=audience_sizes)
    model.age = pyo.Param(model.P, initialize=ages)
    
    # 5. VARIABLES
    model.x = pyo.Var(model.P, model.D, model.S, within=pyo.Binary)
    
    # 6. OBJECTIVE FUNCTION
    def obj_rule(model):
        return sum(model.audience_size[j] * model.x[i, j, k] for i in model.P for j in model.D for k in model.S)
    model.objective = pyo.Objective(rule=obj_rule, sense=pyo.maximize)
    
    # 7. CONSTRAINTS
    
    # Participant Limit: Each participant can be assigned to no more than one debate
    def participant_limit_rule(model, i):
        return sum(model.x[i, j, k] for j in model.D for k in model.S) <= 1
    model.participant_limit = pyo.Constraint(model.P, rule=participant_limit_rule)
    
    # Side Balance: For each debate, the number of participants assigned to the Affirmative side must equal the number assigned to the Negative side
    def side_balance_rule(model, j):
        return sum(model.x[i, j, 'Affirmative'] for i in model.P) == sum(model.x[i, j, 'Negative'] for i in model.P)
    model.side_balance = pyo.Constraint(model.D, rule=side_balance_rule)
    
    # Minimum Participation: Each debate must have at least one participant assigned to it
    def min_participation_rule(model, j):
        return sum(model.x[i, j, k] for i in model.P for k in model.S) >= 1
    model.min_participation = pyo.Constraint(model.D, rule=min_participation_rule)
    
    # Age-Based Constraint: The number of debates a participant can join is limited by their age, specifically by dividing their age by 25
    def age_constraint_rule(model, i):
        return sum(model.x[i, j, k] for j in model.D for k in model.S) <= model.age[i] // 25
    model.age_constraint = pyo.Constraint(model.P, rule=age_constraint_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 i in model.P:
            for j in model.D:
                for k in model.S:
                    if pyo.value(model.x[i, j, k]) > 1e-6:  # Only print non-zero values
                        print(f"x[{i}, {j}, {k}] = {pyo.value(model.x[i, j, k])}")
        
    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
if __name__ == "__main__":
    optimize_debate_assignments()