# Complete PYOMO implementation

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

def optimize_friendships():
    """Optimize mutual friendships in a high school setting"""
    
    # 1. MODEL CREATION
    model = pyo.ConcreteModel()
    
    # 2. DATA SETUP
    # Assume we have 3 students for simplicity
    n_students = 3
    
    # 3. SETS
    model.I = pyo.RangeSet(1, n_students)
    model.J = pyo.RangeSet(1, n_students)
    
    # 4. VARIABLES
    model.x = pyo.Var(model.I, model.J, within=pyo.Binary)
    
    # 5. OBJECTIVE FUNCTION
    def obj_rule(model):
        return sum(model.x[i, j] + model.x[j, i] for i in model.I for j in model.J if i < j)
    model.objective = pyo.Objective(rule=obj_rule, sense=pyo.maximize)
    
    # 6. CONSTRAINTS
    
    # Maximum Friends Constraint
    def max_friends_rule(model, i):
        return sum(model.x[i, j] for j in model.J if i != j) <= 5
    model.max_friends_constraint = pyo.Constraint(model.I, rule=max_friends_rule)
    
    # Mutual Friendship Constraint
    def mutual_friendship_rule(model, i, j):
        if i != j:
            return model.x[i, j] == model.x[j, i]
        else:
            return pyo.Constraint.Skip
    model.mutual_friendship_constraint = pyo.Constraint(model.I, model.J, rule=mutual_friendship_rule)
    
    # 7. 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)
    
    # 8. 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("\nMutual Friendships:")
        for i in model.I:
            for j in model.J:
                if i < j:
                    x_val = pyo.value(model.x[i, j])
                    if x_val > 0.5:  # Only print mutual friendships
                        print(f"Student {i} and Student {j} are mutual friends.")
        
    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
optimize_friendships()