# Complete PYOMO implementation

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

def orchestra_optimization():
    """Orchestra optimization problem using Pyomo"""
    
    # 1. MODEL CREATION
    model = pyo.ConcreteModel()
    
    # 2. DATA SETUP
    show_ids = [101, 102, 103]
    attendances = [150, 250, 350]
    max_performances = [5, 10, 15]
    capacities = [200, 300, 400]
    total_conductor_availability = 20
    
    # CRITICAL: Validate array lengths before indexing
    assert len(show_ids) == len(attendances) == len(max_performances) == len(capacities), "Array length mismatch"
    
    # 3. SETS
    model.Shows = pyo.Set(initialize=show_ids)
    
    # 4. PARAMETERS
    model.Attendance = pyo.Param(model.Shows, initialize={show_ids[i]: attendances[i] for i in range(len(show_ids))})
    model.MaxPerformances = pyo.Param(model.Shows, initialize={show_ids[i]: max_performances[i] for i in range(len(show_ids))})
    model.Capacity = pyo.Param(model.Shows, initialize={show_ids[i]: capacities[i] for i in range(len(show_ids))})
    
    # 5. VARIABLES
    model.Performances = pyo.Var(model.Shows, within=pyo.NonNegativeIntegers)
    
    # 6. OBJECTIVE FUNCTION
    def objective_rule(model):
        return sum(model.Attendance[show] * model.Performances[show] for show in model.Shows)
    model.objective = pyo.Objective(rule=objective_rule, sense=pyo.maximize)
    
    # 7. CONSTRAINTS
    
    # Total availability of conductors
    def conductor_constraint_rule(model):
        return sum(model.Performances[show] for show in model.Shows) <= total_conductor_availability
    model.conductor_constraint = pyo.Constraint(rule=conductor_constraint_rule)
    
    # Orchestra performance limits
    def performance_limit_rule(model, show):
        return model.Performances[show] <= model.MaxPerformances[show]
    model.performance_limit_constraint = pyo.Constraint(model.Shows, rule=performance_limit_rule)
    
    # Venue capacity constraints
    def capacity_constraint_rule(model, show):
        return model.Attendance[show] * model.Performances[show] <= model.Capacity[show]
    model.capacity_constraint = pyo.Constraint(model.Shows, rule=capacity_constraint_rule)
    
    # 8. SOLVING WITH GUROBI
    solver = SolverFactory('gurobi')
    
    # Solve the model
    results = solver.solve(model, tee=True)
    
    # 9. RESULT PROCESSING
    if results.solver.termination_condition == pyo.TerminationCondition.optimal:
        print("Optimal solution found!")
        print(f"Optimal value: {pyo.value(model.objective)}")
        
        # Extract variable values
        print("\nPerformances per show:")
        for show in model.Shows:
            performances_val = pyo.value(model.Performances[show])
            if performances_val > 1e-6:  # Only print non-zero values
                print(f"Performances[{show}] = {performances_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

# Run the optimization
orchestra_optimization()