# Complete PYOMO implementation

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

def orchestra_optimization():
    """Optimize the number of performances for each orchestra to maximize total attendance."""
    
    # 1. MODEL CREATION
    model = pyo.ConcreteModel()
    
    # 2. DATA SETUP
    orchestras = [1, 2, 3]
    attendance = {1: 500, 2: 600, 3: 450}
    min_performances = {1: 1, 2: 2, 3: 1}
    max_performances = {1: 10, 2: 12, 3: 8}
    total_conductor_availability = 300
    
    # CRITICAL: Validate array lengths before indexing
    assert len(attendance) == len(min_performances) == len(max_performances) == len(orchestras), "Array length mismatch"
    
    # 3. SETS (Pyomo way to define indices)
    model.I = pyo.Set(initialize=orchestras)
    
    # 4. PARAMETERS (data containers)
    model.attendance = pyo.Param(model.I, initialize=attendance)
    model.min_performances = pyo.Param(model.I, initialize=min_performances)
    model.max_performances = pyo.Param(model.I, initialize=max_performances)
    
    # 5. VARIABLES
    model.x = pyo.Var(model.I, within=pyo.NonNegativeIntegers)
    
    # 6. OBJECTIVE FUNCTION
    def obj_rule(model):
        return sum(model.attendance[i] * model.x[i] for i in model.I)
    model.objective = pyo.Objective(rule=obj_rule, sense=pyo.maximize)
    
    # 7. CONSTRAINTS - CORRECT SYNTAX PATTERNS
    
    # Conductor Availability Constraint
    def conductor_availability_rule(model):
        return sum(model.x[i] for i in model.I) <= total_conductor_availability
    model.conductor_availability_constraint = pyo.Constraint(rule=conductor_availability_rule)
    
    # Minimum Performances Constraint
    def min_performances_rule(model, i):
        return model.x[i] >= model.min_performances[i]
    model.min_performances_constraint = pyo.Constraint(model.I, rule=min_performances_rule)
    
    # Maximum Performances Constraint
    def max_performances_rule(model, i):
        return model.x[i] <= model.max_performances[i]
    model.max_performances_constraint = pyo.Constraint(model.I, rule=max_performances_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("\nVariable values:")
        for i in model.I:
            x_val = pyo.value(model.x[i])
            if x_val > 1e-6:  # Only print non-zero values
                print(f"x[{i}] = {x_val:.3f}")
        
    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__":
    orchestra_optimization()