# Complete PYOMO implementation - Retry Attempt 4

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

def optimize_friendships():
    # 1. MODEL CREATION
    model = pyo.ConcreteModel()
    
    # 2. DATA SETUP
    # Example data based on the problem context
    persons = [1, 2, 3, 4, 5]
    age_groups = [1, 2, 3]
    age_group_membership = {
        1: [1, 2],
        2: [3, 4],
        3: [5]
    }
    
    # Validate data consistency
    assert len(persons) > 0, "Persons list is empty"
    assert len(age_groups) > 0, "Age groups list is empty"
    
    # 3. SETS
    model.P = pyo.Set(initialize=persons)  # Set of persons
    model.A = pyo.Set(initialize=age_groups)  # Set of age groups
    
    # 4. PARAMETERS
    # Age group membership
    model.age_group_membership = pyo.Param(model.A, initialize=age_group_membership)
    
    # 5. VARIABLES
    # Binary decision variable for friendships
    model.x = pyo.Var(model.P, model.P, within=pyo.Binary)
    
    # 6. OBJECTIVE FUNCTION
    def obj_rule(model):
        return sum(model.x[i, j] for i in model.P for j in model.P if j > i)
    model.objective = pyo.Objective(rule=obj_rule, sense=pyo.maximize)
    
    # 7. CONSTRAINTS
    
    # Constraint 1: Minimum friendships per age group
    def min_friendships_rule(model, i, k):
        return sum(model.x[i, j] for j in model.age_group_membership[k]) >= 3
    model.min_friendships = pyo.Constraint(model.P, model.A, rule=min_friendships_rule)
    
    # Constraint 2: Maximum friendships per person
    def max_friendships_rule(model, i):
        return sum(model.x[i, j] for j in model.P if j != i) <= 15
    model.max_friendships = pyo.Constraint(model.P, rule=max_friendships_rule)
    
    # Constraint 3: Mutual friendships
    def mutual_friendships_rule(model, i, j):
        return model.x[i, j] == model.x[j, i]
    model.mutual_friendships = pyo.Constraint(model.P, model.P, rule=mutual_friendships_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
    if results.solver.termination_condition == pyo.TerminationCondition.optimal:
        print("Optimal solution found!")
        print(f"Optimal value: {pyo.value(model.objective)}")
        
        # Extract variable values
        print("\nFriendships:")
        for i in model.P:
            for j in model.P:
                if j > i and pyo.value(model.x[i, j]) > 0.5:
                    print(f"Person {i} is friends with Person {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_friendships()