# Complete DOCPLEX implementation - Retry Attempt 4

from docplex.mp.model import Model

def optimize_friendships():
    # 1. MODEL & DATA SETUP
    mdl = Model(name="social_network_friendships")
    
    # Example data (replace with actual data from database)
    users = [1, 2, 3, 4, 5]
    age_groups = {1: [1, 2], 2: [3, 4], 3: [5]}  # Example mapping of age groups to users
    max_friendships = 15
    min_friendships_per_age_group = 3
    
    # 2. VARIABLES
    friendships = mdl.binary_var_dict([(i, j) for i in users for j in users if i < j], name="friendship")
    
    # 3. OBJECTIVE FUNCTION
    total_friendships = mdl.sum(friendships[(i, j)] for i in users for j in users if i < j)
    mdl.maximize(total_friendships)
    
    # 4. CONSTRAINTS
    # Constraint 1: Minimum friendships per age group
    for i in users:
        for age_group, members in age_groups.items():
            mdl.add_constraint(mdl.sum(friendships[(i, j)] for j in members if i < j) + 
                              mdl.sum(friendships[(j, i)] for j in members if j < i) >= min_friendships_per_age_group,
                              ctname=f"min_friendships_age_group_{i}_{age_group}")
    
    # Constraint 2: Maximum friendships per person
    for i in users:
        mdl.add_constraint(mdl.sum(friendships[(i, j)] for j in users if i < j) + 
                          mdl.sum(friendships[(j, i)] for j in users if j < i) <= max_friendships,
                          ctname=f"max_friendships_{i}")
    
    # Constraint 3: Mutual friendships
    for i in users:
        for j in users:
            if i < j:
                mdl.add_constraint(friendships[(i, j)] == friendships[(j, i)], ctname=f"mutual_friendship_{i}_{j}")
    
    # 5. SOLVING & RESULTS
    solution = mdl.solve()
    
    if solution:
        print(f"Optimal value: {solution.objective_value}")
        for (i, j), value in friendships.items():
            if solution.get_value(friendships[(i, j)]) > 0.5:
                print(f"Friendship between {i} and {j}: {value}")
    else:
        print("No solution found")
        print(f"Status: {mdl.solve_details.status}")

# Execute the optimization
optimize_friendships()