#!/usr/bin/env python3
"""
Pyomo 6.9.2 Implementation for Music Ensemble Performance Attendance Optimization
"""

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

def optimize_performance_attendance():
    """Optimize the number of pieces each member performs to maximize attendance."""
    
    # 1. MODEL CREATION
    model = pyo.ConcreteModel()
    
    # 2. DATA SETUP
    members = [1, 2, 3]
    performances = [1, 2, 3]
    
    # Member constraints
    max_pieces_member = {1: 5, 2: 4, 3: 3}
    
    # Performance constraints
    max_pieces_performance = {1: 10, 2: 8, 3: 6}
    
    # Attendance data
    attendance = {1: 200, 2: 150, 3: 100}
    
    # CRITICAL: Validate array lengths before indexing
    assert len(members) == len(max_pieces_member), "Member data length mismatch"
    assert len(performances) == len(max_pieces_performance) == len(attendance), "Performance data length mismatch"
    
    # 3. SETS
    model.M = pyo.Set(initialize=members)  # Members
    model.P = pyo.Set(initialize=performances)  # Performances
    
    # 4. PARAMETERS
    model.max_pieces_member = pyo.Param(model.M, initialize=max_pieces_member)
    model.max_pieces_performance = pyo.Param(model.P, initialize=max_pieces_performance)
    model.attendance = pyo.Param(model.P, initialize=attendance)
    
    # 5. VARIABLES
    model.x = pyo.Var(model.M, model.P, within=pyo.NonNegativeIntegers)
    
    # 6. OBJECTIVE FUNCTION
    def obj_rule(model):
        return sum(model.attendance[p] * model.x[m, p] for m in model.M for p in model.P)
    model.objective = pyo.Objective(rule=obj_rule, sense=pyo.maximize)
    
    # 7. CONSTRAINTS
    
    # Maximum Pieces per Member
    def max_pieces_member_rule(model, m):
        return sum(model.x[m, p] for p in model.P) <= model.max_pieces_member[m]
    model.max_pieces_member_constraint = pyo.Constraint(model.M, rule=max_pieces_member_rule)
    
    # Maximum Pieces per Performance
    def max_pieces_performance_rule(model, p):
        return sum(model.x[m, p] for m in model.M) <= model.max_pieces_performance[p]
    model.max_pieces_performance_constraint = pyo.Constraint(model.P, rule=max_pieces_performance_rule)
    
    # Minimum Pieces per Member
    def min_pieces_member_rule(model, m):
        return sum(model.x[m, p] for p in model.P) >= 1
    model.min_pieces_member_constraint = pyo.Constraint(model.M, rule=min_pieces_member_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
    # 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("\nVariable values:")
        for m in model.M:
            for p in model.P:
                x_val = pyo.value(model.x[m, p])
                if x_val > 1e-6:  # Only print non-zero values
                    print(f"x[{m}, {p}] = {x_val:.0f}")
        
    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__":
    optimize_performance_attendance()