# Complete PYOMO implementation

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

def singer_optimization():
    """Optimization model for maximizing song promotion sales increase"""
    
    # 1. MODEL CREATION
    model = pyo.ConcreteModel()
    
    # 2. DATA SETUP
    # Data from the problem context
    potential_sales_increase = [1200.0, 1800.0, 2500.0]
    promotion_costs = [600.0, 900.0, 1200.0]
    budget = 2000.0  # Example budget
    max_songs = 2    # Example maximum number of songs to promote
    
    # Validate array lengths
    n_songs = len(potential_sales_increase)
    assert len(promotion_costs) == n_songs, "Array length mismatch"
    
    # 3. SETS
    model.Songs = pyo.RangeSet(1, n_songs)
    
    # 4. PARAMETERS
    model.potential_sales_increase = pyo.Param(model.Songs, initialize={i+1: potential_sales_increase[i] for i in range(n_songs)})
    model.promotion_costs = pyo.Param(model.Songs, initialize={i+1: promotion_costs[i] for i in range(n_songs)})
    
    # 5. VARIABLES
    model.promote = pyo.Var(model.Songs, within=pyo.Binary)
    
    # 6. OBJECTIVE FUNCTION
    def objective_rule(model):
        return sum(model.potential_sales_increase[i] * model.promote[i] for i in model.Songs)
    model.objective = pyo.Objective(rule=objective_rule, sense=pyo.maximize)
    
    # 7. CONSTRAINTS
    # Budget constraint
    def budget_constraint_rule(model):
        return sum(model.promotion_costs[i] * model.promote[i] for i in model.Songs) <= budget
    model.budget_constraint = pyo.Constraint(rule=budget_constraint_rule)
    
    # Promotion limit constraint
    def promotion_limit_rule(model):
        return sum(model.promote[i] for i in model.Songs) <= max_songs
    model.promotion_limit = pyo.Constraint(rule=promotion_limit_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)
    
    # 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("\nPromotion decisions:")
        for i in model.Songs:
            promote_val = pyo.value(model.promote[i])
            print(f"Song {i}: {'Promote' if promote_val > 0.5 else 'Do not promote'}")
        
    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
singer_optimization()