# Complete DOCPLEX implementation

from docplex.mp.model import Model

def optimize_mutual_friendships():
    """Optimize mutual friendships in a high school setting"""
    
    # 1. MODEL & DATA SETUP
    mdl = Model(name="mutual_friendships")
    
    # Assume we have 3 students for simplicity
    n_students = 3
    
    # CRITICAL: Validate array lengths to prevent IndexError
    # Here, we assume a complete graph for simplicity, so no need for array length checks
    safe_range = range(n_students)
    
    # 2. VARIABLES
    # Binary decision variables for friendships
    x = {(i, j): mdl.binary_var(name=f"x_{i}_{j}") for i in safe_range for j in safe_range if i != j}
    
    # 3. OBJECTIVE FUNCTION
    # Maximize the number of mutual friendships
    objective = mdl.sum(x[i, j] for i in safe_range for j in safe_range if i < j)
    mdl.maximize(objective)
    
    # 4. CONSTRAINTS - CORRECT SYNTAX PATTERNS
    
    # Maximum Friends Constraint: Each student can have at most 5 friends
    for i in safe_range:
        mdl.add_constraint(mdl.sum(x[i, j] for j in safe_range if i != j) <= 5, ctname=f"max_friends_{i}")
    
    # Mutual Friendship Constraint: Friendships must be mutual
    for i in safe_range:
        for j in safe_range:
            if i != j:
                mdl.add_constraint(x[i, j] == x[j, i], ctname=f"mutual_{i}_{j}")
    
    # 5. SOLVING & RESULTS
    solution = mdl.solve()
    
    if solution:
        print(f"Optimal value: {solution.objective_value}")
        for i in safe_range:
            for j in safe_range:
                if i != j:
                    value = solution.get_value(x[i, j])
                    if value > 1e-6:
                        print(f"x[{i},{j}] = {value:.3f}")
    else:
        print("No solution found")
        print(f"Status: {mdl.solve_details.status}")
    
    return mdl

# Run the optimization
optimize_mutual_friendships()