# Complete PYOMO implementation

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

def concert_singer_optimization():
    """Optimize singer assignments to concerts in stadiums to maximize audience capacity."""
    
    # 1. MODEL CREATION
    model = pyo.ConcreteModel()
    
    # 2. DATA SETUP
    # Example data from the problem context
    stadium_capacities = [10000, 20000, 30000]  # Capacities of stadiums
    singer_assignments = [0, 1, 0, 1, 0]  # Initial assignments (binary)
    singer_limit = 2  # Maximum number of concerts a singer can participate in
    
    # CRITICAL: Validate array lengths before indexing
    n_stadiums = len(stadium_capacities)
    n_assignments = len(singer_assignments)
    assert n_stadiums > 0, "No stadiums provided"
    assert n_assignments > 0, "No singer assignments provided"
    
    # 3. SETS (Pyomo way to define indices)
    model.I = pyo.RangeSet(1, n_assignments)  # Singers (1-based indexing)
    model.J = pyo.RangeSet(1, n_stadiums)  # Stadiums (1-based indexing)
    
    # 4. PARAMETERS (data containers)
    model.stadium_capacity = pyo.Param(model.J, initialize={j: stadium_capacities[j-1] for j in model.J})
    model.singer_limit = pyo.Param(initialize=singer_limit)
    
    # 5. VARIABLES
    # Binary decision variable: x[i,j] = 1 if singer i is assigned to stadium j, 0 otherwise
    model.x = pyo.Var(model.I, model.J, within=pyo.Binary)
    
    # 6. OBJECTIVE FUNCTION
    # Maximize the total audience capacity
    def obj_rule(model):
        return sum(model.stadium_capacity[j] * model.x[i, j] for i in model.I for j in model.J)
    model.objective = pyo.Objective(rule=obj_rule, sense=pyo.maximize)
    
    # 7. CONSTRAINTS
    
    # Constraint 1: Singer Assignment Limit
    def singer_limit_rule(model, i):
        return sum(model.x[i, j] for j in model.J) <= model.singer_limit
    model.singer_limit_constraint = pyo.Constraint(model.I, rule=singer_limit_rule)
    
    # Constraint 2: Stadium Capacity Limit
    def stadium_capacity_rule(model, j):
        return sum(model.x[i, j] for i in model.I) <= model.stadium_capacity[j]
    model.stadium_capacity_constraint = pyo.Constraint(model.J, rule=stadium_capacity_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:
            for j in model.J:
                if pyo.value(model.x[i, j]) > 0.5:  # Only print assignments
                    print(f"Singer {i} assigned to Stadium {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

# Run the optimization
if __name__ == "__main__":
    concert_singer_optimization()