# Complete PYOMO implementation

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

def singer_optimization():
    """Optimization problem for selecting singers to maximize sales."""
    
    # 1. MODEL CREATION
    model = pyo.ConcreteModel()
    
    # 2. DATA SETUP
    singers = [1, 2, 3]
    sales = {1: 1500, 2: 2500, 3: 1000}
    net_worth = {1: 200000, 2: 300000, 3: 150000}  # Placeholder values
    total_budget = 500000
    max_singers = 3
    
    # CRITICAL: Validate array lengths before indexing
    assert len(singers) == len(sales) == len(net_worth), "Array length mismatch"
    
    # 3. SETS (Pyomo way to define indices)
    model.I = pyo.Set(initialize=singers)
    
    # 4. PARAMETERS (data containers)
    model.sales = pyo.Param(model.I, initialize=sales)
    model.net_worth = pyo.Param(model.I, initialize=net_worth)
    
    # 5. VARIABLES
    model.x = pyo.Var(model.I, within=pyo.Binary)
    
    # 6. OBJECTIVE FUNCTION
    def obj_rule(model):
        return sum(model.sales[i] * model.x[i] for i in model.I)
    model.objective = pyo.Objective(rule=obj_rule, sense=pyo.maximize)
    
    # 7. CONSTRAINTS
    
    # Budget Constraint
    def budget_rule(model):
        return sum(model.net_worth[i] * model.x[i] for i in model.I) <= total_budget
    model.budget_constraint = pyo.Constraint(rule=budget_rule)
    
    # Promotional Capacity Constraint
    def capacity_rule(model):
        return sum(model.x[i] for i in model.I) <= max_singers
    model.capacity_constraint = pyo.Constraint(rule=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("\nSelected Singers:")
        for i in model.I:
            if pyo.value(model.x[i]) > 0.5:  # Only print selected singers
                print(f"Singer {i} is selected.")
        
    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__":
    singer_optimization()