#!/usr/bin/env python3
"""
Pyomo 6.9.2 Implementation for Student Friendship Optimization
"""

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

def student_friendship_optimization():
    """Optimize student friendships to maximize happiness score."""
    
    # 1. MODEL CREATION
    model = pyo.ConcreteModel()
    
    # 2. DATA SETUP
    # Happiness scores from the HappinessScore table
    happiness_scores = {
        (1, 2): 1,
        (2, 3): 1,
        (3, 1): 1,
        (1, 3): 0,
        (2, 1): 0
    }
    
    # List of students
    students = [1, 2, 3]
    
    # Business configuration parameters
    min_friends = 2
    max_friends = 5
    
    # CRITICAL: Validate array lengths before indexing
    assert len(students) > 0, "No students provided"
    
    # 3. SETS (Pyomo way to define indices)
    model.I = pyo.Set(initialize=students)  # Set of students
    
    # 4. PARAMETERS (data containers)
    model.happiness_score = pyo.Param(model.I, model.I, initialize=happiness_scores, default=0)
    
    # 5. VARIABLES
    # Binary decision variables for friendships
    model.x = pyo.Var(model.I, model.I, within=pyo.Binary)
    
    # 6. OBJECTIVE FUNCTION
    def obj_rule(model):
        return sum(model.happiness_score[i, j] * model.x[i, j] for i in model.I for j in model.I)
    model.objective = pyo.Objective(rule=obj_rule, sense=pyo.maximize)
    
    # 7. CONSTRAINTS - CORRECT SYNTAX PATTERNS
    
    # Minimum Friends Constraint
    def min_friends_rule(model, i):
        return sum(model.x[i, j] for j in model.I) >= min_friends
    model.min_friends_constraint = pyo.Constraint(model.I, rule=min_friends_rule)
    
    # Maximum Friends Constraint
    def max_friends_rule(model, i):
        return sum(model.x[i, j] for j in model.I) <= max_friends
    model.max_friends_constraint = pyo.Constraint(model.I, rule=max_friends_rule)
    
    # Mutual Friendship Constraint
    def mutual_friendship_rule(model, i, j):
        return model.x[i, j] == model.x[j, i]
    model.mutual_friendship_constraint = pyo.Constraint(model.I, model.I, rule=mutual_friendship_rule)
    
    # 8. SOLVING WITH GUROBI (your available solver)
    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("\nFriendship pairings:")
        for i in model.I:
            for j in model.I:
                if i < j and pyo.value(model.x[i, j]) == 1:
                    print(f"Student {i} is friends with Student {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}")
    
    return model

# Execute the optimization
if __name__ == "__main__":
    student_friendship_optimization()